I have an array of objects ($itemObjectArray
), each one having these properties and some values like so:
ID : 1234
Location : USA
Price : $500
Color : Blue
I have a SQL Server 2012 table called Items
with column names that match the object property names like so:
TABLE Items (
ID
Location
Price
Color
PRIMARY KEY (ID)
)
I have created the following code to insert the object into the SQL Server table. I think my code is a little crude. Is there a more elegant way to do this since the column names match the object property names?
$itemObjectArray | %{ #step through array
#get property names, which match column names
$names = $_ | Get-Member -membertype properties
Foreach($name in $names.name){ #make SQL string for column names
$cols += $name + ","
}
$cols = $cols.trimend(",") #get rid of last comma
Foreach($name in $names.name){
#step through properties, get values and build values string
$vals += "'" + $_.$($name) + "',"
}
$vals = $vals.trimend(",") #get rid of last comma
$sqlCommand.CommandText = "INSERT INTO Items ($cols) VALUES ($vals)"
$sqlCommand.ExecuteNonQuery() #insert
$cols = $Null #wipe
$vals = $Null
}