开发者

PowerShell 101: unexpected result using select-object piped into set-content

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)',开发者_如何学JAVA '$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-Object produces 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, but Set-Content is writing the actual scriptblocks.

If you change one little part of your script to pipe the output of Select-Object to a Foreach-Object (using the scriptblock as the body of the foreach), it will produce your desired output. Change this part of the first line:

select-object -first 3 {

To this:

select-object -first 3 | foreach {

Your final script should look like this:

import-csv .\CdmCodeList.csv | select-object -first 3 | foreach { 
    $id = $_.ItemDescription.Replace("'", "''");
    $mn = $_.ManufacturerName.Replace("'", "''");
    $mc = $_.ManufacturerCode.Replace("'", "''");
    "insert into @codes values ('$($_.ItemCode)', '$id', '$mn', '$mc')";
} | set-content -path "my.sql"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜