Powershell省略了CRLF输出,并带有'out-file'



Powershell在写入文件时省略CRLF

下面的重现代码

$part1 = "this is one line
This is a second line 
this is not
"
$part2 = "this is almost the last line
this is the last line."
$code =  $part1
$code += $part2
$code
$code  | out-file "test.cs" 
notepad test.cs

当我在记事本中查看输出时,与命令提示符相比,CRLF 换行符丢失。

这里的问题是在控制台上按 Enter 不会在字符串中间产生 CRLF,而只会产生 LF。您需要将 CRLF ('r'n( 字符添加到字符串中,或者以不同的方式构建它们。下面的方法只是用 CRLF 替换 LF 或 CRLF 序列。我使用 -join 运算符来组合字符串。

$part1 = "this is one line
This is a second line 
this is not
"
$part2 = "this is almost the last line
this is the last line."
$code = -join ($part1 -replace "r?n","`r`n"),($part2 -replace "r?n","`r`n")
$code  | out-file "test.cs" 
notepad test.cs

您可以将变量构建为字符串数组。然后,当通过管道访问对象时,CRLF 将在输出时自动添加到每个元素。

$part1 = "this is one line","This is a second line","this is not"
$part2 = "this is almost the last line","this is the last line."
$code = $part1 + $part2
$code | out-file test.cs

您还可以使用 -split 运算符拆分 LF 或 CRLF 字符。请记住,$part1 + $part2之所以有效,是因为您在$part1末尾有一个 LF .

$part1 = "this is one line
This is a second line 
this is not
"
$part2 = "this is almost the last line
this is the last line."
$code = ($part1 + $part2) -split "r?n"
$code | out-file test.cs

最新更新