Powershell替换存储在许多文件夹中的多个文件中的文本

ast*_*_zh 8 directory powershell replace file

我想替换多个文件和文件夹中的文本.文件夹名称更改,但文件名始终为config.xml.

$fileName = Get-ChildItem "C:\config\app*\config.xml" -Recurse
(Get-Content $fileName) -replace 'this', 'that' | Set-Content $fileName
Run Code Online (Sandbox Code Playgroud)

当我运行上面的脚本时,它可以工作,但它在config.xml中写入整个文本大约20次.怎么了?

Loï*_*HEL 14

$ filename是一个集合System.IO.FileInfo objects.你必须循环以获取每个文件的内容:这应该做你想要的:

$filename | %{
    (gc $_) -replace "THIS","THAT" |Set-Content $_.fullname
}
Run Code Online (Sandbox Code Playgroud)


mjo*_*nor 6

$ filename是一个文件名数组,它试图一次完成所有这些操作.尝试一次一个:

$fileNames = Get-ChildItem "C:\config\app*\config.xml" -Recurse |
 select -expand fullname

foreach ($filename in $filenames) 
{
  (  Get-Content $fileName) -replace 'this', 'that' | Set-Content $fileName
}
Run Code Online (Sandbox Code Playgroud)


Max*_*lle 6

通常,您应该使用管道并组合ForEach-Object和/或Where-ObjectCmdLet。

在您的情况下,这更类似于:

Get-ChildItem "C:\config\app*\config.xml" -Recurse | ForEach-Object -Process {
    (Get-Content $_) -Replace 'this', 'that' | Set-Content $_
}
Run Code Online (Sandbox Code Playgroud)

可以稍微缩短为:

dir "C:\config\app*\config.xml" -recurse |% { (gc $_) -replace 'this', 'that' | (sc $_) }
Run Code Online (Sandbox Code Playgroud)