45

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?

4

5 回答 5

63

`n是换行符。记事本(在 Windows 10 之前)需要将换行符编码为`r`n(回车 + 换行,CR-LF)。在一些有用的编辑器(SciTENotepad++UltraEdit-32Vim、...)中打开文件并将换行符转换为 CR-LF。或使用 PowerShell:

(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath
于 2013-07-02T19:39:20.580 回答
21

您可以使用Environment 类的静态 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
于 2013-07-02T20:34:34.527 回答
17

也可以将换行符和回车符分配给变量,然后将它们附加到 PowerShell 脚本内的文本中:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg
于 2015-01-28T05:04:07.487 回答
4

尝试这个;

Add-Content -path $logpath @"
$((get-date).tostring()) Error $keyPath $value
key $key expected: $policyValue
local value is:  $localValue
"@
于 2017-07-26T14:15:19.710 回答
1

使用 Pipe 命令时,值对我不起作用。我创建了一个附加的 Add-Content,其 -Value of nothing "" 后跟原始 Get | 添加我正在尝试使用的内容。

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

Add-Content -Path "$newfile" -value ""
Get-Content -Path "$oldfile | Add-Content -Path "$newfile"
于 2021-04-03T22:57:23.343 回答