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-Objecthere:otherwise there is no
$_. As a general rule,$_exists only within script blocks, not directly in the pipeline. AlsoWrite-Hostoperates 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:
(using aliases, string variable interpolation and the fact that strings just fall out of the pipeline to the host)