开发者

Format each line of command output in powershell

开发者 https://www.devze.com 2023-04-11 20:51 出处:网络
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) :

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

精彩评论

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

关注公众号