51

I'm creating an error log file. This is my current code:

Add-Content -path $logpath $((get-date).tostring() + " Error " + $keyPath `
   + $value + " key " + $key +" expected: " + $policyValue `
   + "`n local value is: " +$localValue

When I Get-Content on the log file, it displays correctly, with the new line before "local value."

However, when I open the log file in Notepad, it displays everything on a single line. How can I cause it to insert a new line into the text file as well?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
NewPowerSheller
  • 523
  • 1
  • 4
  • 5

6 Answers6

68

`n is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n (carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:

(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
21

You can use the Environment class's static NewLine property to get the proper newline:

$errorMsg =  "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
               (Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg
Aaron Jensen
  • 25,861
  • 15
  • 82
  • 91
19

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rchacko
  • 1,965
  • 23
  • 24
4

Try this;

Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is:  $localValue
"@
Steztric
  • 2,832
  • 2
  • 24
  • 43
  • The @ symbol changes how the text inside of the "'s are read. With the @'s the text is read 'as is'. Which means no additional processing is done to the text, and the newlines characters are included too. – TinyRacoon Jan 29 '19 at 11:23
2

Values were not working for me when using Pipe command. I Created an additional Add-Content with -Value of nothing "" followed by the original Get | Add that I was trying to use.

$newfile = "C:\FilePath\Newfile.txt" 
$oldfile = "C:\FilePath\Oldfile.txt"

Add-Content -Path "$newfile" -value ""
Get-Content -Path "$oldfile | Add-Content -Path "$newfile"
Heph
  • 21
  • 2
0
"Line-1$([Environment]::NewLine)`"Line-2`"$([Environment]::NewLine)Line-3"| out-File c:\Temp\abc.txt 

enter image description here

enter image description here

Hemendr
  • 673
  • 6
  • 12