2012-10-16 80 views
1

我試圖從一個變量grep的一些數據字符串:轉換的ArrayList在PowerShell中

Select-String -inputObject $patternstring -Pattern $regex -AllMatches 
| % { $_.Matches } | % { $_.Value } -OutVariable outputValue 
Write-Host $outputValue 

要在同一outvariable,我試圖做的字符串操作

$outputValue.Substring(1,$outputValue.Length-2); 

失敗,說明outputValue是一個ArrayList

如何將Arraylist轉換爲String

+1

您是否曾嘗試先在$ outputValue上執行連接? Ala $($ outputValue -join「't」)這會給你串行化爲一個製表符分隔字符串的數組列表值。 –

回答

1

嘗試這樣的:

$outputvalue = Select-String -inputObject $patternstring -Pattern $regex -AllMatches | 
       % { $_.Matches } | % { $_.Value } 

$outputValue | % { $_.Substring(1 ,$_.Length - 2)} 

參數-outvariableForEach-Object似乎並沒有捕捉處理的sciptblock的輸出(這在PowerShell中V2;感謝給@ShayLevi測試它在V3的作品) 。

+0

+1,無論如何,我認爲你需要在結果爲集合的情況下將結果傳遞給foreach,否則子字符串將失敗。 –

+0

@shayLevy當然!忘了粘貼rigth命令。編輯我的答案..再次:) –

1

如果輸出是值的集合,那麼無論結果的類型是什麼,子字符串都會失敗。嘗試管道到Foreach-Object,然後使用子串。

UPDATE:

的OutputVariable僅適用於V3,看到V2 @Christian解決方案。

Select-String -InputObject $patternstring -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } -OutVariable outputValue 

$outputValue | Foreach-Object { $_.Substring(1,$_.Length-2) } 
+0

我測試了這種方式,但似乎在這個foreach中'-outvariable'沒有填充。你能證實這個問題嗎?謝謝 –

+0

你說得對,我正在測試v3,它工作。它在V2中失敗了。無論如何,結果是System.String,而不是ArrayList。 –

+0

感謝您在V2上進行測試。 –

4

正如sean_m的評論中提到,最容易做的事情是簡單地首先使用-join運算符將字符串轉換爲一個字符串的System.Collections.ArrayList:

$outputValue = $($outputValue -join [Environment]::NewLine) 

一旦你已經完成了這個操作,你可以在$ outputValue上執行任何常規的字符串操作,比如Substring()方法。

上面我用新行分隔了ArrayList中的每個字符串,因爲這通常是-OutVariable在將字符串轉換爲ArrayList時分割字符串的字符串,但是如果您想要使用不同的分隔符字符串。