2

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"

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.