批量修改文件编码时PowerShell提示文件被占用错误
解决批量修改.GER文件编码时的文件占用问题
问题原因
你遇到的错误是因为同一进程内同时对文件进行读和写操作:原命令中Get-Content通过管道传递内容给Set-Content时,文件句柄还未被Get-Content完全释放,Set-Content就尝试写入同一个文件,导致冲突。Process Explorer检测不到外部进程占用,是因为占用来自PowerShell自身的读操作。
解决方案
方案1:先读取内容到变量再写入
修改PowerShell命令,先把文件内容存入变量,再执行写入操作,断开读操作与文件的关联:
powershell -command "$apb=(Get-Content config_temp\path.txt)+'\APBGame\Localization\GER\'; Get-ChildItem $apb -Filter *.GER -Recurse | Foreach-Object { $content = Get-Content $_.FullName; Set-Content -Encoding utf8 -Path $_.FullName -Value $content }"
方案2:使用.NET文件类直接操作(更稳定)
用System.IO.File类的静态方法读写,避免管道操作带来的句柄延迟释放问题:
powershell -command "$apb=(Get-Content config_temp\path.txt)+'\APBGame\Localization\GER\'; Get-ChildItem $apb -Filter *.GER -Recurse | Foreach-Object { $content = [System.IO.File]::ReadAllText($_.FullName); [System.IO.File]::WriteAllText($_.FullName, $content, [System.Text.Encoding]::UTF8) }"
方案3:优化路径拼接(避免潜在的路径错误)
用Join-Path安全拼接路径,防止原路径末尾带斜杠导致的双斜杠问题:
powershell -command "$basePath = Get-Content config_temp\path.txt; $apb = Join-Path $basePath 'APBGame\Localization\GER'; Get-ChildItem $apb -Filter *.GER -Recurse | Foreach-Object { $content = Get-Content $_.FullName; Set-Content -Encoding utf8 $_.FullName -Value $content }"
后续改回UTF16-LE的参考命令
完成findstr读取后,用类似逻辑改回编码:
powershell -command "$apb=(Get-Content config_temp\path.txt)+'\APBGame\Localization\GER\'; Get-ChildItem $apb -Filter *.GER -Recurse | Foreach-Object { $content = Get-Content $_.FullName; Set-Content -Encoding unicode $_.FullName -Value $content }"
注:PowerShell中-Encoding unicode对应UTF16-LE编码。
内容的提问来源于stack exchange,提问作者leiseg
相关产品推荐
相关产品推荐

