Powershell此处字符串换行符不适用于输出文件

时间:2019-01-10 13:25:16

标签: powershell

我有300行的文本在此处以字符串形式定义为:

$outputText = @"
Line1
Line2
Line3
And so on...
"@

如果我在屏幕上打印$outputText,则显示正确:

PS > $outputText
Line1
Line2
Line3
And so on...
PS > 

但是,当我尝试将其输出到文件中时,我总是会丢失换行符,文件看起来像这样:

Line1Line2Line3And so on...

我尝试遵循:

$outputText | Set-Content file.txt
Add-Content file.txt -Value $outputText
Out-File -InputObject $outputText file.txt

如果我在每行的末尾添加'r'n(带有适当的刻度),则可见输出在每行之间会有额外的换行符,但是输出文件正确显示了每行。但是,在几百行中的每行之后放置回车和换行符并不是一个真正的选择。

我如何能够更轻松地正确地将换行符输出到文件中,或者以其他方式定义多行字符串,从而使换行符在没有复杂的转义符等情况下也能正常工作?

3 个答案:

答案 0 :(得分:4)

此处的字符串将文本放入 ONE 字符串中,并以LF / 0xA分隔行。

$outputText = @"
Line1
Line2
Line3
And so on...
"@
$outputText | Format-Hex

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   4C 69 6E 65 31 0A 4C 69 6E 65 32 0A 4C 69 6E 65  Line1.Line2.Line
00000010   33 0A 41 6E 64 20 73 6F 20 6F 6E 2E 2E 2E 0D 0A  3.And so on.....

相反,分割字符串:

$outputText = @"
Line1
Line2
Line3
And so on...
"@ -split '\n'  # or -split "`n"

$outputText | Set-Content file1.txt
Out-File -InputObject $outputText file2.txt

1..2|%{(Get-Content ".\file$_.txt" -raw) | Format-Hex}

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   4C 69 6E 65 31 0D 0A 4C 69 6E 65 32 0D 0A 4C 69  Line1..Line2..Li
00000010   6E 65 33 0D 0A 41 6E 64 20 73 6F 20 6F 6E 2E 2E  ne3..And so on..
00000020   2E 0D 0A                                         ...


           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   4C 69 6E 65 31 0D 0A 4C 69 6E 65 32 0D 0A 4C 69  Line1..Line2..Li
00000010   6E 65 33 0D 0A 41 6E 64 20 73 6F 20 6F 6E 2E 2E  ne3..And so on..
00000020   2E 0D 0A                                         ...

其他可能影响输出的因素(不在此处)


> $OutputEncoding


IsSingleByte      : True
BodyName          : us-ascii
EncodingName      : US-ASCII
HeaderName        : us-ascii
WebName           : us-ascii
WindowsCodePage   : 1252
IsBrowserDisplay  : False
IsBrowserSave     : False
IsMailNewsDisplay : True
IsMailNewsSave    : True
EncoderFallback   : System.Text.EncoderReplacementFallback
DecoderFallback   : System.Text.DecoderReplacementFallback
IsReadOnly        : True
CodePage          : 20127

PS :在VSCode中运行第二个脚本返回了0D / 0D / 0A序列,必须使用-split '\r\n'

答案 1 :(得分:0)

对于多行字符串也是如此。另一种方法。将Unix文本(`n)转换为Windows文本(`r`n)。

$outputtext = @"
Line1
Line2
Line3
And so on...
"@ -replace "`n","`r`n"

仔细检查:

$outputtext -replace '\n','\n' -replace '\r','\r'

Line1\r\nLine2\r\nLine3\r\nAnd so on...

-replace的第一个参数可以使用反斜杠或反引号。

答案 2 :(得分:0)

$FilePath = YourOutputFilePath
$InputString = 'This is my text with new lines.
It would be nice to have new lines in my text file output.
Also, to preserve this formatting.'   
Out-File -FilePath $FilePath -InputObject $InputString.Replace("`n", "`r`n") -Encoding unicode -Append -Force

这对我来说很好。