如何使用PowerShell替换多个文件中的文本并将每个文件保存在新文件夹中?

如何使用PowerShell替换多个文件中的文本并将每个文件保存在新文件夹中?,powershell,Powershell,我有一个包含多个文件的文件夹。我希望读取每个文件并替换为用户传递给应用程序的任何文件(参数)。替换文件内容后,我想将文件保存在新文件夹中 这就是我到目前为止所做的: gci C:\Users\Person\Documents\Test1\*.bat -recurse | ForEach { (Get-Content $_ | ForEach {$_ -replace "<client_instance>", "ClientName"}) | Set-Content $_ }

我有一个包含多个文件的文件夹。我希望读取每个文件并替换为用户传递给应用程序的任何文件(参数)。替换文件内容后,我想将文件保存在新文件夹中

这就是我到目前为止所做的:

gci C:\Users\Person\Documents\Test1\*.bat -recurse | ForEach {
  (Get-Content $_ | ForEach {$_ -replace "<client_instance>", "ClientName"}) | Set-Content $_ 
}

我是PowerShell的新手,因此非常感谢您的帮助。谢谢。

是的,您的代码很好。您可以按如下方式构建新路径:

$files = gci C:\Users\Person\Documents\Test1\*.bat -recurse
$destinationpath = "C:\users\person\documents\test2"
ForEach ($file in $files){
    Get-Content $file.fullname | ForEach {$_ -replace "<client_instance>", "ClientName"} | set-content "$destinationpath\$($file.basename)"
}
$files=gci C:\Users\Person\Documents\Test1\*.bat-recurse
$destinationpath=“C:\users\person\documents\test2”
ForEach($files中的文件){
获取内容$file.fullname | ForEach{$\替换“”“ClientName”}设置内容“$destinationpath\$($file.basename)”
}

您可能需要在这里和那里调整它以满足您的需要。

这很有效。非常感谢。我只需要为目标文件类型添加“.bat”。我可以在3分钟内接受您的回答。为什么需要更改为“输出文件”?您可以同样轻松地执行
设置内容“$destinationpath\$($file.basename)”
。主要的一点是
getcontent$124; |…|Set Content$\uz
覆盖源文件。我绝对不想替换原始文件。我想用替换的值创建一个副本。@您完全正确,我以某种方式从字面上理解了“更改集内容”。编辑了我的答案,以便更简洁地说明需要更改的内容。@RJ。正当您使用的
设置内容$
的问题不是
设置内容
,而是为
-Path
参数
$\ucode>传递的值。
$files = gci C:\Users\Person\Documents\Test1\*.bat -recurse
$destinationpath = "C:\users\person\documents\test2"
ForEach ($file in $files){
    Get-Content $file.fullname | ForEach {$_ -replace "<client_instance>", "ClientName"} | set-content "$destinationpath\$($file.basename)"
}