2010-06-17 80 views
0

我想读取一个csv文件,根据两个字段的值对其进行过滤,并设置另一个字段的值。下面是我想要实现一个简单的例子 :Powershell:设置过滤数组的值

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"> 

我怎样才能做到这一点。如您所见,从示例中,我可以读取 并对数组进行过滤。但是我不知道如何设置第三场的值为 。我尝试了set-itemproperty,但得到错误:“在关闭管道 后,无法调用 WriteObject和WriteError方法”。

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

任何意见,如何实现这一点,将不胜感激。

艾伦牛逼

回答

4

我改变你的代码一点点:

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

注意自我:确保CSV中的标题行没有尾随空间......这使我在过去几分钟的测试中失去了... – Joey 2010-06-17 16:31:17

+0

谢谢stej工作过。 – 2010-06-17 16:47:39

2

你有正确的想法。使用Where-Object(化名到哪里),以进一步过滤管道中的对象,然后顺着管道使用Foreach-Object(化名为的foreach)来设置值,像这样:位置对象的

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

想象的那样只是一个过滤器机制和Foreach-Object作为管道机制,允许您将任意脚本应用于每个管道对象。

+0

感谢Keith的帮助。 – 2010-06-17 16:49:08