複数のファイル内のテキストを置換すると重複エラーが発生する

複数のファイル内のテキストを置換すると重複エラーが発生する

現在のフォルダー内のすべてのファイル (このテストでは 2 つ) をループして、テキストを置き換えます。

置換は機能していますが、file1 には newfile1 と newfile2 が残り、file 2 にも同じものが残ります。必要なのは、file 1 には newfile 1、file 2 には newfile 2 だけです。

ForEach-Object が間違った場所にあると思われますが、修正できません。何か提案はありますか?

@echo off
call:DoReplace "a1" "a2" *.txt "a3" "a4" 
exit /b

:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 -replace %4, %5} ^| Set-Content %3>Rep.ps1 
Powershell.exe -executionpolicy ByPass -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
echo Done
pause

答え1

これは見た目は良くありませんが、機能します:

Get-ChildItem \\path\to\folder -Filter '*.txt' | foreach {
$text = Get-Content $_.FullName
$text = $text -replace 'a2','test'
$text = $text -replace 'a4','foo'
$text | Set-Content $_.FullName
}

スクリプトの問題は、Set-Contentループする必要があることですForEach-Object

関連情報