Last active
March 16, 2020 15:16
-
-
Save JesperJ/5c92cde49fe192692035dc8f2f078ab4 to your computer and use it in GitHub Desktop.
Insert custom object to Database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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