How do I add a newline to command output in PowerShell? How do I add a newline to command output in PowerShell? powershell powershell

How do I add a newline to command output in PowerShell?


Or, just set the output field separator (OFS) to double newlines, and then make sure you get a string when you send it to file:

$OFS = "`r`n`r`n""$( gci -path hklm:\software\microsoft\windows\currentversion\uninstall |     ForEach-Object -Process { write-output $_.GetValue('DisplayName') } )" |  out-file addrem.txt

Beware to use the ` and not the '. On my keyboard (US-English Qwerty layout) it's located left of the 1.
(Moved here from the comments - Thanks Koen Zomers)


Give this a try:

PS> $nl = [Environment]::NewLinePS> gci hklm:\software\microsoft\windows\currentversion\uninstall |         ForEach { $_.GetValue("DisplayName") } | Where {$_} | Sort |        Foreach {"$_$nl"} | Out-File addrem.txt -Enc ascii

It yields the following text in my addrem.txt file:

Adobe AIRAdobe Flash Player 10 ActiveX...

Note: on my system, GetValue("DisplayName") returns null for some entries, so I filter those out. BTW, you were close with this:

ForEach-Object -Process { "$_.GetValue("DisplayName") `n" }

Except that within a string, if you need to access a property of a variable, that is, "evaluate an expression", then you need to use subexpression syntax like so:

Foreach-Object -Process { "$($_.GetValue('DisplayName'))`r`n" }

Essentially within a double quoted string PowerShell will expand variables like $_, but it won't evaluate expressions unless you put the expression within a subexpression using this syntax:

$(`<Multiple statements can go in here`>).


I think you had the correct idea with your last example. You only got an error because you were trying to put quotes inside an already quoted string. This will fix it:

gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output ($_.GetValue("DisplayName") + "`n") }

Edit: Keith's $() operator actually creates a better syntax (I always forget about this one). You can also escape quotes inside quotes as so:

gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output "$($_.GetValue(`"DisplayName`"))`n" }