【问题标题】:Powershell Get-Content -> Foreach-Object -> -replace ->Out-File is adding a char (0x00) to the start of every filePowershell Get-Content -> Foreach-Object -> -replace ->Out-File 在每个文件的开头添加一个字符(0x00)
【发布时间】:2013-04-15 21:02:32
【问题描述】:

我有一个在文件中执行正则表达式替换的函数。问题是它会在它接触的每个文件的开头添加一个字符(0x00)(即使是那些它找不到匹配的文件!)。由于我正在编辑 csproj 文件,MSBuild 给了我这个错误:

error MSB4025: The project file could not be loaded. '.', hexadecimal value 0x00, is an invalid character. Line 2, position 1.

这是我的功能:

function fileStringRegExReplace ([string] $fileToChange, [string] $oldString, [string] $newString) {
    echo "f" | xcopy "$fileToChange" "$fileToChange.og.cs" /Y /Q

    $file = Get-Content "$fileToChange.og.cs" | 
        Foreach-Object {
            $_ -replace $oldString, $newString
        } |
        Out-File "$fileToChange"

    Remove-Item "$fileToChange.og.cs"
}

如何替换我想要的行而不更改文件的任何其他部分?

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    听起来好像是在文件开头写了一个BOM。您可以使用out-file 上的-Encoding ASCII 参数将编码设置为ASCII(没有BOM)。

    【讨论】:

    • 由于我不知道的原因 Set-Content 默认生成 ASCII 文件,Out-File 创建 UCS-2 little endian 文件。 related。我创建了一个Get-FileEncoding 函数,该函数试图确定源文件编码是什么,以便它可以与-Encoding 参数和Set-ContentOut-File 一起使用,这对于像这样的文件更新很有用。
    • 在更改为 Set-Content 或使用 Out-File -Encoding ASCII 后,我仍然遇到问题。我也在替换 csproj 文件中的文本。
    • 有一个解决方案,现在发布。
    【解决方案2】:

    Out-File 的默认编码是 Unicode,即 Windows 中的 UTF-16。只写ASCII集合中的字符时,UTF-16基本上有在每个字符前面加一个0x00字节的效果。这就解释了为什么 Visual Studio 抱怨 0x00 字节。

    您尝试修改的 csproj 文件的 XML 声明为 UTF-8,因此请在 Out-File 中使用 -Encoding UTF8 选项。

    不要使用 ASCII 编码,一旦 csproj 文件中包含非 ASCII 字符,这将导致问题。

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,在使用 ForEach 替换文本后,我遇到了问题。

      对于我的解决方案,我只想找到最后一个 </Target> 并添加附加另一个 <Target></Target>

      我尝试了这种方法,但由于某种原因文件大小增加了一倍,并且在 Line: 2, Position: 1 处也出现了 0x00 错误。

      我必须在这个解决方案上归功于 @Matt,因为我自己可能无法弄清楚正则表达式:https://stackoverflow.com/a/28437855/740575

      这让我可以优雅地不使用ForEach 方法。你应该在这个解决方案的某个地方找到你的答案。

      $replaceVar = "<Target> ... </Target" ;
      # NOTE: -Raw will read the entire file in as a string, without doing that
      #       everything gets read in as an array of lines
      $file = Get-Content file.csproj -Raw ;
      $newFile = $file -replace "(?s)(.*)</Target>(.*)", "$1$replaceVar$2" ;
      
      # csproj is UTF8
      $newFile | Out-File -Encoding UTF8 "new.csproj" ;
      

      解决方案适用于 Visual Studio 和 msbuild.exe

      【讨论】:

        【解决方案4】:

        尝试用 set-content 替换 out-file。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-13
          • 2017-02-04
          • 1970-01-01
          相关资源
          最近更新 更多