Find and replacing strings in multiple files

2019-07-25 08:24发布

问题:

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
}

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

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!

回答1:

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}