Powershell:设置过滤数组的值

时间:2010-06-17 16:16:34

标签: arrays powershell csv

我想在csv文件中读取,根据两个值对其进行过滤 字段并设置另一个字段的值。这是一个简单的例子 我想要实现的目标:

c:\ somefile.csv内容:

firstField,secondField,thirdField
1,2,"somevalue"
2,2,"avalue"
3,1,"somevalue"

#Import file into array
$csv = Import-Csv c:\somefile.csv

# Where secondField = 2 and thirdField = "someValue" set thirdField =
"anotherValue"
$csv | where {$_secondField -eq 2 -and $_.thirdField = "somevalue"} |
<set value of thirdField = "anotherValue">

我该怎么做?如您所见,从示例中,我可以阅读 in并过滤数组。但我不知道如何设置值 第三个领域。我尝试了set-itemproperty,但得到了错误:“ 管道之后无法调用WriteObject和WriteError方法 已被关闭“。

编辑:我也只想更改返回的前2项(行)的值。 我回答:我使用了Select -first 2。

关于如何实现这一点的任何建议都将受到赞赏。

Alan T

2 个答案:

答案 0 :(得分:4)

我改变了你的代码:

$csv | 
    Where-Object {$_.secondField -eq 2 -and $_.thirdField -eq 'somevalue'} |
    Foreach-Object { $_.thirdField = 'anotherValue' }
  • $_secondField =&gt; $_.secondField
  • $_.thirdField = "somevalue"应为$_.thirdField -eq "somevalue"
  • Foreach-Object设置第三个值。在这种情况下它只处理1条记录,但基本上它处理所有管道传输的记录(只是尝试删除Where部分)。
  • 由于意外的变量扩展,使用单引号而不是双引号更“安全”。

答案 1 :(得分:2)

你有正确的想法。使用Where-Object(别名为Where)过滤管道中的对象,然后使用Foreach-Object(别名为Foreach)进一步向下管道设置值,如下所示:

$csv | where {$_secondField -eq 2 -and $_.thirdField -eq "somevalue"} | 
    foreach {$_.thirdField = "notherValue"}

将Where-Object视为一种过滤机制,将Foreach-Object视为允许您将任意脚本应用于每个管道对象的管道机制。