开发者

Format each line of command output in powershell

How can I format each line of Get-ChildItem output ? For instance I would like to surround it with my own strings, to get the following output (plain - no tables or whatever) :

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

Following is not working:

Get-ChildItem | Write-Host "My开发者_开发技巧 string " + $_ + " my string2"


You need ForEach-Object here:

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

otherwise there is no $_. As a general rule, $_ exists only within script blocks, not directly in the pipeline. Also Write-Host operates on multiple arguments and you cannot concatenate strings in command mode, therefore you either need to add parentheses to get one argument in expression mode or leave out the quotes and + (as I did here).

Shorter:

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

(using aliases, string variable interpolation and the fact that strings just fall out of the pipeline to the host)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜