46

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,030
  • 21
  • 100
  • 124
NewPowerSheller
  • 473
  • 1
  • 4
  • 5

5 Answers5

64

`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
  • 184,186
  • 23
  • 230
  • 299
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
  • 24,214
  • 15
  • 75
  • 88
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,030
  • 21
  • 100
  • 124
rchacko
  • 1,839
  • 21
  • 23
4

Try this;

Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is:  $localValue
"@
Steztric
  • 2,692
  • 1
  • 23
  • 40
  • 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
1

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
  • 11
  • 2