PowerShell 输出文件:防止编码更改
我目前正在研究一些搜索和替换操作,我正在尝试使用 powershell 自动化这些操作。不幸的是,我昨天意识到我们的代码库中有不同的文件编码(UTF8 和 ASCII)。因为我们是在不同的分支中执行这些搜索和替换操作,所以我无法在此阶段更改文件编码。
如果我运行以下几行,即使我的默认 powershell 编码设置为 iso-8859-1(西欧 (Windows)),它也会将所有文件更改为 UCS-2 Little Eindian。
$content = Get-Content $_.Path
$content -replace 'myOldText' , 'myNewText' | Out-File $_.Path
有没有办法阻止 powershell 更改文件的编码?
I'm currently working on some search and replace operation that I'm trying to automate using powershell. Unfortunately I recognized yesterday that we've different file encodings in our codebase (UTF8 and ASCII). Because we're doing these search and replace operations in a different branch I can't change the file encodings at this stage.
If I'm running the following lines it changes all files to UCS-2 Little Eindian even though my default powershell encoding is set to iso-8859-1 (Western European (Windows)).
$content = Get-Content $_.Path
$content -replace 'myOldText' , 'myNewText' | Out-File $_.Path
Is there a way to prevent powershell from changing the file's encoding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Out-File
具有默认编码,除非使用-Encoding
参数覆盖:我为解决此问题所做的就是尝试通过读取来获取原始文件的编码读取它的字节顺序标记并将其用作
-Encoding
参数值。这是一个处理一堆文本文件路径、获取原始编码、处理内容并使用原始编码将其写回文件的示例。
更新 下面是使用 StreamReader 类获取原始文件编码的示例。该示例读取文件的前 3 个字节,以便根据其内部 BOM 检测例程的结果设置
CurrentEncoding
属性。http://msdn.microsoft.com/en-us/library/9y86s1a9.aspx
http://msdn.microsoft.com/en-us /library/system.text.encoding.getpreamble.aspx
Out-File
has a default encoding unless overriden with the-Encoding
parameter:What I've done to solve this is to try to get the original file's encoding by reading trying to read it's byte order mark and using it as the
-Encoding
parameter value.Here's an example processing a bunch of text file paths, getting the original encoding, processing the content and writing it back to file with the original's encoding.
Update Here is an example of getting the original file encoding using the StreamReader class. The example reads the first 3 bytes of the file so that the
CurrentEncoding
property gets set based on the result of its internal BOM detection routine.http://msdn.microsoft.com/en-us/library/9y86s1a9.aspx
http://msdn.microsoft.com/en-us/library/system.text.encoding.getpreamble.aspx