2011-10-08 45 views
2

如何格式化Get-ChildItem輸出的每一行?舉例來說,我想用我自己的字符串包圍它,得到下面的輸出(普通 - 沒有桌子或其他):在powershell中格式化每行命令輸出

My string: C:\File.txt my string2 
My string: C:\Program Files my string2 
My string: C:\Windows my string2 

以下是不工作:

Get-ChildItem | Write-Host "My string " + $_ + " my string2" 

回答

4

你需要ForEach-Object這裏:

Get-ChildItem | ForEach-Object { Write-Host My string $_.FullName my string2 } 

否則就沒有$_。通常,$_僅存在於腳本塊中,而不是直接存在於管道中。此外,Write-Host對多個參數進行操作,並且您不能在命令模式下連接字符串,因此您需要在表達式模式中添加括號以獲取一個參數,或者省略引號和+(正如我在此處所做的那樣)。

短:

gci | % { "My string $($_.FullName) my string2" } 

(使用別名,字符串變量插值而事實上,串正好落在了管道到主機)

+0

謝謝,它的工作。我喜歡第二種形式 –