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换行符。
答案 0 :(得分: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