【问题标题】:How to replace many .mbt files with encoding UTF-8 BOM to UTF-8 with powershell如何使用powershell将许多将UTF-8 BOM编码为UTF-8的.mbt文件替换
【发布时间】:2021-08-27 06:01:24
【问题描述】:

我在一个目录中有许多扩展名为 .mbt 的文件,目前我的同事使用 notepad++ 编辑每个文件以将编码从 UTF-8 BOM 更改为 UTF-8 非常耗时,因为这些文件会进一步导入软件和不适用于编码 UTF-8 BOM。

所以我找到了一个 powershell 脚本,它将脚本中指定的文件替换为具有正确编码的新文件,但因为它不能解决我的问题,并且由于我对 powershell 脚本缺乏了解,我无法弄清楚如何制作它用另一个文件替换文件而不更改其名称,但只更改编码并对指定目录中的所有文件执行此操作。

这是执行我解释的当前代码:

function Remove-BomFromFile ($OldPath, $NewPath)
{
  $Content = Get-Content $OldPath -Raw
  $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
  [IO.File]::WriteAllLines($NewPath, $Content, $Utf8NoBomEncoding)
}
$Path = "C:\Users\slavkovs\Desktop\test\Z_00154_.mbt"
$NewPath = "C:\Users\slavkovs\Desktop\test\Z_00154_New.mbt"
Remove-BomFromFile -OldPath $Path -NewPath $NewPath

[CmdletBinding()]
param(  
    [Parameter(Mandatory=$true)]
    [string]$path,
    [Parameter(Mandatory=$false)]
    [string]$dest = $path,
    [Parameter(Mandatory=$true)]
    [string]$encoding
)

【问题讨论】:

    标签: powershell encoding


    【解决方案1】:

    利用IO.File类的.Net方法.WriteAllText()默认写入不带BOM的UTF-8这一事实,你可以使用这个:

    $rootDirectory = 'D:\Test'    # path where the .mbt files are to be found
    Get-ChildItem -Path $rootDirectory -Filter '*.mbt' -File | ForEach-Object {
        [System.IO.File]::WriteAllText($_.FullName, ([System.IO.File]::ReadAllText($_.FullName)))
    }
    

    【讨论】:

    • 完美运行,非常感谢!!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2012-07-19
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2013-09-12
    相关资源
    最近更新 更多