Maciej Wozniak
Maciej Wozniak

Reputation: 1174

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"

Upvotes: 2

Views: 2941

Answers (1)

Joey
Joey

Reputation: 354396

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)

Upvotes: 4

Related Questions