You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整PowerShell脚本以支持带空格路径及条件UTF-8编码

Param (
    [Parameter(Mandatory=$True)][String]$Diretorio
)

# 编码检测函数:判断文件是否为UTF-8编码(兼容有BOM和无BOM格式)
function Test-UTF8Encoding {
    param([string]$FilePath)
    $reader = New-Object System.IO.StreamReader($FilePath, [System.Text.Encoding]::UTF8, $true)
    $reader.Peek() | Out-Null
    $encoding = $reader.CurrentEncoding
    $reader.Close()
    return $encoding.WebName -eq "utf-8"
}

# 自动拼接路径,兼容空格、特殊字符与不同系统的路径分隔符
$targetPath = Join-Path -Path $Diretorio -ChildPath "*"

Get-ChildItem -Path $targetPath -Recurse -Include *.srt,*.txt | ForEach-Object {
    # 仅非UTF-8编码文件执行转码
    if (-not (Test-UTF8Encoding -FilePath $_.FullName)) {
        $content = Get-Content -Path $_.FullName -Raw
        Set-Content -Path $_.FullName -Value $content -Encoding UTF8 -Force
    }
}

调整说明

  • 支持带空格的路径:不再使用手动拼接$Diretorio\*的写法,改用Join-Path完成路径拼接,自动处理路径中的空格、特殊字符,避免路径被拆分为多个参数导致运行报错。
  • 智能跳过已为UTF-8编码的文件:新增编码检测逻辑,通过.NET的StreamReader类识别文件真实编码,只有检测结果不是UTF-8时才执行转码,避免重复编码损坏文件内容。

内容的提问来源于stack exchange,提问作者saravo7056

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:57:03