选择-Property与字符串数组和自定义列脚本块?

时间:2015-04-16 19:30:22

标签: powershell

我有以下脚本。

$cols = Get-MyColumns # returns "a","b","c",...
$cols2 = $cols, @{n='x'; e={"0"}} # Add a new column
import-csv test.csv | select -property $cols2

但是脚本会出现以下错误。

select : Cannot convert System.Object[] to one of the following types {System.String, 
System.Management.Automation.ScriptBlock}.
At line:1 char:xx
+ Import-Csv test.csv | select -Property $cols2
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], NotSupportedException
    + FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand

字符串数组不能与自定义列定义连接。它的解决方法是什么?

1 个答案:

答案 0 :(得分:1)

在您计算的属性中,您需要使用分号分隔NameExpression。您还需要组合“字段”,以便将它们作为一维数组传递给-Property参数。

select -Property ($cols + @{n='x';e={0}})

属性需要单个字符串或数组。更改$cols的定义也会有效

$cols = "a","b","c",@{n='x';e={"0"}}

如果您不关心新列的值,您可以放入任何内容来创建空列。

$cols = "a","b","c","doesnotexist"

例如:

a b c doesnotexist
- - - ------------
1 2 3             
4 5 6 
相关问题