PowerShell 管道 Get-Content 拆分然后 select 表达式
PowerShell pipeline Get-Content to split and then select expression
我有一个文件,我想拆分 selective 行并取 selective 单元格。
这项工作:
Get-Content F:\dat | ? {$_ -like "1,*"} | % {$_.Split(',')}
但我无法继续连接 select 一些项目:
Get-Content F:\dat | ? {$_ -like "1,*"} | % {$_.Split(',')} | Select -Property @{name="Name"; expression = {$_[0]}}, @{name="Value"; expression = {$_[5]}}
我收到了意外的结果,例如这样的文件:
1,"123",456,"bla bla bla",0,569.2
排除结果:
Name Value
1 569.2
1 569.2
完成的结果:
Name Value
---- ----
1
"
4
" b
0
5
如果一切都崩溃了:
| % {$_.Split(',')} |
管道中的下一个命令将只接收单个字符串的可枚举流(拆分操作的结果),而不是字符串数组。
因此,$_[0]
操作被解析为 "Take the first [char] from this string",这就是您看到奇怪输出的原因。
等到你真正计算出属性再拆分字符串:
Get-Content F:\dat | ? {$_ -like "1,*"} | Select -Property @{name="Name"; expression = {$_.Split(',')[0]}}, @{name="Value"; expression = {$_.Split(',')[5]}}
您可以只使用 ConvertFrom-Csv
来代替:
Get-Content F:\dat|
Where-Object {$_ -like "1,*"}|
ConvertFrom-Csv -Header Name,Ignore1,Ignore2,Ignore3,Ignore4,Value|
Select-Object Name,Value
我有一个文件,我想拆分 selective 行并取 selective 单元格。
这项工作:
Get-Content F:\dat | ? {$_ -like "1,*"} | % {$_.Split(',')}
但我无法继续连接 select 一些项目:
Get-Content F:\dat | ? {$_ -like "1,*"} | % {$_.Split(',')} | Select -Property @{name="Name"; expression = {$_[0]}}, @{name="Value"; expression = {$_[5]}}
我收到了意外的结果,例如这样的文件:
1,"123",456,"bla bla bla",0,569.2
排除结果:
Name Value
1 569.2
1 569.2
完成的结果:
Name Value
---- ----
1
"
4
" b
0
5
如果一切都崩溃了:
| % {$_.Split(',')} |
管道中的下一个命令将只接收单个字符串的可枚举流(拆分操作的结果),而不是字符串数组。
因此,$_[0]
操作被解析为 "Take the first [char] from this string",这就是您看到奇怪输出的原因。
等到你真正计算出属性再拆分字符串:
Get-Content F:\dat | ? {$_ -like "1,*"} | Select -Property @{name="Name"; expression = {$_.Split(',')[0]}}, @{name="Value"; expression = {$_.Split(',')[5]}}
您可以只使用 ConvertFrom-Csv
来代替:
Get-Content F:\dat|
Where-Object {$_ -like "1,*"}|
ConvertFrom-Csv -Header Name,Ignore1,Ignore2,Ignore3,Ignore4,Value|
Select-Object Name,Value