Skip to content

Instantly share code, notes, and snippets.

@JesperJ
Last active March 16, 2020 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JesperJ/5c92cde49fe192692035dc8f2f078ab4 to your computer and use it in GitHub Desktop.
Save JesperJ/5c92cde49fe192692035dc8f2f078ab4 to your computer and use it in GitHub Desktop.
Insert custom object to Database
function Write-SqlTableFromObj {
<#
.SYNOPSIS
Insert custom object to Database
.DESCRIPTION
Assume PSCustomObject key names is SQL Table column names and inserts values to SQL Table
.PARAMETER ServerInstance
SQL Server Instance
.PARAMETER Database
SQL Server Database
.PARAMETER TableName
SQL Table to Insert into
.PARAMETER Data
Custom Object(s) to import in SQLTable
.EXAMPLE
$data = @(@{ID=1; Namn="Gunde"}, @{ID=2; Namn="Barbro"})
Write-SqlTableFromObj @SQLSettings -Data $Data
.EXAMPLE
$data = @(@{ID=1; Namn="Gunde"}, @{ID=2; Namn="Barbro"})
$data | Write-SqlTableFromObj @SQLSettings
.NOTES
General notes
#>
[CmdletBinding()]
param (
[parameter(Mandatory = $True)]
$ServerInstance,
[parameter(Mandatory = $True)]
$Database,
[parameter(Mandatory = $True)]
$TableName,
[parameter(ValueFromPipeline = $True, Mandatory = $True)]
[PSCustomObject[]]
$Data
)
begin {
$SQLConnStr = @{
ServerInstance = $ServerInstance
Database = $Database
}
}
process {
foreach ($Row in $Data) {
$Columns = $Row.Keys -join ','
$Values = $Row.Values -join "','"
$SQLString = "INSERT INTO [$($TableName)] ($($Columns)) VALUES ('$($Values)')"
Write-Verbose $SQLString
Invoke-Sqlcmd @SQLConnStr -Query $SQLString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment