繁体   English   中英

在 PowerShell 中使用 Set-Content 多个文件保持相同的编码

[英]Keep Same Encoding With Set-Content Multiple Files in PowerShell

我正在尝试编写一个脚本,用于将应用程序从服务器迁移到服务器和/或从一个驱动器号迁移到另一个驱动器号。 我的目标是从一个位置复制目录,将其移动到另一个位置,然后运行脚本来编辑旧主机名、IP 地址和驱动器号的所有实例,以反映新主机名、IP 地址和驱动器号在新服务器。 这似乎正是这样做的:

ForEach($File in (Get-ChildItem $path\* -Include *.xml,*.config -Recurse)){
    (Get-Content $File.FullName -Raw) -replace [RegEx]::Escape($oldhost),$newhost `
                                 -replace [RegEx]::Escape($oldip),$newip `
                                 -replace "$olddriveletter(?=:\Application)",$newDriveLetter | 
     Set-Content $File.FullName -NoNewLine
}

我遇到的一个问题是文件都有不同类型的编码。 一些 ANSI、一些 UTF-8、一些 Unicode 等。当我运行脚本时,它会将所有内容保存为 ANSI,然后我的应用程序无法工作。 我知道如何添加 encoding 参数,但是有没有办法在每个单独的文件上保持相同的编码,而不用写出一个脚本来指定目录中的每个单独文件和每个单独文件的编码?

那会很困难。 get-content 没有传递编码属性太糟糕了。 这是一个脚本,如果有签名,它会尝试获取编码。 也许你可以先运行它并检查它们。 但是有些windows文件是unicode no bom。 至少 xml 文件可以说出编码。 get-childitem *.xml | select-string encoding get-childitem *.xml | select-string encoding可能有更好的方法来加载 xml 文件,请参阅底部答案: Powershell: Setting Encoding for Get-Content Pipeline

# encoding.ps1
# https://stackoverflow.com/questions/3825390/effective-way-to-find-any-files-encoding
param([Parameter(ValueFromPipeline=$True)] $filename)
process {
  $reader = [IO.StreamReader]::new($filename, [Text.Encoding]::default,$true)
  $peek = $reader.Peek()
  $encoding = $reader.currentencoding
  $reader.close()
  [pscustomobject]@{Name=split-path $filename -leaf
                BodyName=$encoding.BodyName
            EncodingName=$encoding.EncodingName}
}
# end encoding.ps1


PS C:\users\me> get-childitem chinese16.txt | encoding

Name          BodyName EncodingName
----          -------- ------------
chinese16.txt utf-16   Unicode

像这样的东西将使用 xml 文件中指示的编码,即使它事先没有真正匹配。 (这也使 xml 变得漂亮。)

PS C:\users\me> [xml]$xml = get-content file.xml
PS C:\users\me> $xml.save("$pwd\file.xml")

使用 git 二进制文件中的 file.exe 找出编码。 然后,使用 if else 语句将 encoding 参数添加到 set-content 行以满足您的需要。

ForEach($File in (Get-ChildItem $path\*)){
    $Content = Get-Content $File.FullName -Raw -replace [RegEx]::Escape($oldhost),$newhost `
                                 -replace [RegEx]::Escape($oldip),$newip `
                                 -replace "$olddriveletter(?=:\Application)",$newDriveLetter 
    $Encoding = file --mime-encoding $File
    $FullName = $File.FullName
    Write-Host "$FullName - $Encoding"
    if(-NOT ($Encoding -like "UTF")){
        Set-Content $Content -NoNewLine -Encoding UTF8
    }
    else {
        Set-Content $Content -NoNewLine 
    }
}

参考: https : //docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/set-content http://gnuwin32.sourceforge.net/packages/file.htm

暂无
暂无

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

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