Here’s my powershell script; I think the intent is pretty obvious:
import-csv .\CdmCodeList.csv | select-object -first 3 {
$id = $_.ItemDescription.Replace("'", "''");
$mn = $_.ManufacturerName.Replace("'", "''");
$mc = $_.ManufacturerCode.Replace("'", "''");
"insert into @codes values ('$($_.ItemCode)', '$id', '$mn', '$mc')";
}
This does what I expect, outputting to the host:
insert into @codes values ('37025012', 'SAW BLADE PROFIX', '', '')
insert into @codes values ('37067808', 'ROD SUPER FLEX DANEK', '', '')
insert into @codes values ('52600200', 'GENERATOR PRECISION SCS ADVANCED BIONICS', '', '')
Now if I want to dump that to a file by adding this to the last line:
| set-content -path "my.sql"
The resulting content of my.sql is not what I want, and very surprising to me:
@{
$id = $_.ItemDescription.Replace("'", "''");
$mn = $_.ManufacturerName.Replace("'", "''");
$mc = $_.ManufacturerCode.Replace("'", "''");
"insert into @codes values ('$($_.ItemCode)', '$id', '$mn', '$mc')";
=insert into @codes values ('37025012', 'SAW BLADE PROFIX', '', '')}
@{
$id = $_.ItemDescription.Replace("'", "''");
$mn = $_.ManufacturerName.Replace("'", "''");
$mc = $_.ManufacturerCode.Replace("'", "''");
"insert into @codes values ('$($_.ItemCode)', '$id', '$mn', '$mc')";
=insert into @codes values ('37067808', 'ROD SUPER FLEX DANEK', '', '')}
...etc...
Two questions: 1. What is PowerShell doing? and 2. How can I get the file output to look like the host output?
Select-Objectproduces objects. In the case of your script, it is producing scriptblocks. When you output to host, it is executing the scriptblocks in order to produce the output, butSet-Contentis writing the actual scriptblocks.If you change one little part of your script to pipe the output of
Select-Objectto aForeach-Object(using the scriptblock as the body of theforeach), it will produce your desired output. Change this part of the first line:To this:
Your final script should look like this: