简体   繁体   English

Powershell省略了“输出文件”的CRLF输出

[英]Powershell omits CRLF output with 'out-file'

Powershell omits the CRLF when writing to a file 当写入文件时,Powershell忽略CRLF

Repro code below 下面的复制代码

$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

When I view the output in Notepad, vs the command prompt, the CRLF line breaks are missing. 当我在记事本和命令提示符中查看输出时,缺少CRLF换行符。

The issue here is pressing enter at the console doesn't yield a CRLF in the middle of a string only an LF. 这里的问题是在控制台上按Enter键不会在字符串中间产生CRLF,而只是产生LF。 You either need to add the CRLF (`r`n) characters to your strings or build them differently. 您要么需要在字符串中添加CRLF(`r`n)字符,要么以其他方式构建它们。 The method below simply replaces LF or CRLF sequences with CRLF. 下面的方法仅用CRLF替换LF或CRLF序列。 I use the -join operator to combine the strings. 我使用-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

You could build your variables as an array of strings. 您可以将变量构建为字符串数组。 Then when accessing the objects through the pipeline, the CRLF will automatically be added to each element at output. 然后,当通过管道访问对象时,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

You could also use the -split operator to split on the LF or CRLF characters. 您也可以使用-split运算符来分割LF或CRLF字符。 Keep in mind that the $part1 + $part2 only works because you have an LF at the end of $part1 . 请记住, $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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM