Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 查找和替换多个文件中的字符串_Powershell_Replace - Fatal编程技术网

Powershell 查找和替换多个文件中的字符串

Powershell 查找和替换多个文件中的字符串,powershell,replace,Powershell,Replace,我有一个文件夹,我想搜索所有文件,找到特定的字符串,并替换这些字符串。我目前使用以下函数 Function replacement($old, $new, $location){ $configFiles = Get-ChildItem $ApplicationFolder\* -include *.xml,*.config,*.bat,*.ini -rec foreach ($file in $configFiles){ Try { (Get-Con

我有一个文件夹,我想搜索所有文件,找到特定的字符串,并替换这些字符串。我目前使用以下函数

Function replacement($old, $new, $location){
$configFiles = Get-ChildItem $ApplicationFolder\* -include *.xml,*.config,*.bat,*.ini -rec 

foreach ($file in $configFiles){
        Try {
            (Get-Content $file.pspath) | ForEach-Object {$_ -replace $old, $new} | Set-Content $file.pspath
        }
        Catch {
        $tempfile = Convert-Path -path $file.PSPath
        $message = "`nCould not replace $old in " + $tempfile +". This is usually caused by a permissions issue. The string may or may not exist."
        $message
        }
}
}
不幸的是,此函数读取和写入文件夹中的所有文件,而不仅仅是包含字符串的文件

我正在努力使脚本更高效,并使它在下面几行中抛出更少的权限错误

Function replacement($old, $new, $location){
Get-ChildItem $location -include *.xml,*.config,*.bat,*.ini -rec | Select-String -pattern     $old | Get-Content $_.path | ForEach-Object {$_ -replace $old, $new} | Set-Content $_.path
}
我遇到的问题是使用管道选择字符串来获取内容。它传递的对象不能有效地表示文件对象

我尝试了使用管道选择字符串来
格式化表-属性路径-force-HideTableHeaders
和其他一些东西,但我还没有真正做到这一点

我想听听你的意见。
谢谢

筛选出不匹配的文件,如下所示:

$configFiles = Get-ChildItem $ApplicationFolder\* -include *.xml,*.config,*.bat,*.ini -rec | Where {Select-String $old $_.FullName -Quiet}

非常感谢你的帮助。这当然给了我翻山所需的动力。这是我最后一句话。只适合任何想找类似东西的人<代码>函数替换($old、$new、$location){