2010-06-17 42 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