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

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

问题描述:

我有一个文件夹,我想搜索所有文件、查找特定字符串并替换这些字符串.我目前使用以下功能.

I have a folder that I want to search through all files, find specific strings, and replace those strings. I currently use the following function.

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
        }
}
}

不幸的是,此函数读取和写入文件夹中的所有文件——而不仅仅是包含字符串的文件.

This function unfortunately reads and writes to all files in the folder--not just the ones that contain the string.

我正在尝试使脚本更高效,并使用以下几行减少权限错误.

I am trying to make the script more efficient and have it throw less permissions errors with the lines below.

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
}

我遇到的问题是将 Select-String 传递给 Get-Content.它传递的对象不能有效地表示文件对象.

The problem I'm having is piping Select-String to Get-Content. The object that it passes does not validly represent the file object.

我已经尝试将 Select-String 管道传输到 Format-Table -Property path -force -HideTableHeaders 和其他一些东西,但我还没有真正做到.

I've tried piping Select-String to Format-Table -Property path -force -HideTableHeaders and a few other things but I haven't really gotten far with it.

我希望得到一些意见.谢谢!

I would appreciate some opinions. Thanks!

像这样过滤掉不匹配的文件:

Filter out files that don't match like so:

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