Powershell 7 - Set-Content and Out-file 向我的文件添加回车符 (CR)

标签 powershell scripting

我正在使用 Get-Content 命令操作文件,进行替换,然后将其通过管道传输到 Set-Content 或 Out-File。但是在我所有的换行符之前,文件都是用 CR 写入的。我的原始文件有换行符,这没问题,但 CR 破坏了文件的用途。

我试过这个 Powershell replace content in file adds redundent carriage return

但无法让它工作。如果可能,我想避免使用 .NET

这是我的代码:

(Get-Content "FILE.TEMPLATE") -replace('SEQUENCE', "$NEWSEQUENCE") | Set-Content ("FILE.NEW")

(Get-Content "FILE.TEMPLATE") -replace('SEQUENCE', "$NEWSEQUENCE") | Set-Content ("FILE.NEW") -Encoding UTF8NoBOM

我尝试在 Set-Content 管道之后使用“-Encoding”设置编码,但这没有任何作用。试过 UTF8、UTF8NoBOM。这个输出文件注定要在 UNIX 机器上使用,这就是 CR 破坏文件的原因。

有什么想法吗?

最佳答案

经过更多的挖掘,这才是有效的

(Get-Content "FILE.TEMPLATE" -Raw) -replace 'SEQUENCE', "$NEWSEQUENCE" | 
  Set-Content "FILE.NEW" -NoNewLine -Encoding UTF8NoBOM

必须将 -Raw 添加到 Get-Content,然后将 -NoNewLine-Encoding UTF8NoBOM 添加到 Set-Content.

这仅适用于 PowerShell 6+,因为以下任何内容都没有 UTF8NoBOM 作为编码选项。 Powershell 5 默认为 UTF8BOM

关于Powershell 7 - Set-Content and Out-file 向我的文件添加回车符 (CR),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60749120/

相关文章:

python 目录装饰器

调用 `exit` 时 Bash 脚本不会立即退出

powershell - PowerShell 的快速 ping 功能

git - 无法使用 Powershell 推送到 github

linux - 将 ls -R 输出解析为 Unix 中的变量

batch-file - PowerShell 将文件大小显示为 KB、MB 或 GB

authentication - 在不使用公钥身份验证或期望的情况下自动化 SSH(1)

.net - Powershell:调用 .NET 函数总是需要括号吗?

powershell - 如何让 Azure PowerShell 记住命令行历史记录?

sharepoint - SharePoint Online-默认情况下启用网站功能