Powershell省略了'out-file'的CRLF输出

问题描述 投票:0回答:1

Powershell在写入文件时省略了CRLF

下面的Repro代码

$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换行符。

powershell
1个回答
1
投票

这里的问题是在控制台上按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
© www.soinside.com 2019 - 2024. All rights reserved.