Home > OS >  Consolidates the contents of the files instead of editing one by one
Consolidates the contents of the files instead of editing one by one

Time:03-07

$file = 'G\*\configs.txt'
$find = '192.168.152.161:8011'
$replace = '{appconfigs.writes}'

(Get-Content $file).replace($find, $replace) | Set-Content $file

When I run the edit script on all the files together The script unites them and does not edit one by one.

what can we do?

CodePudding user response:

You are trying to potentially process multiple files. Therefore, you cannot use Get-Content straight away. You need to wrap this in a loop.

Here is an example on how to do this.

$find = '192.168.152.161:8011'
$replace = '{appconfigs.writes}'

foreach ($File in Get-ChildItem -Path 'G\*\configs.txt') {
    $Content = Get-Content -Path $File.FullName -Raw
    #IndexOf to avoid using Set-Content on files that did not change
    if ($Content.IndexOf($find) -gt -1) {
        $Content.replace($find, $replace) | Set-Content $file.FullName
    }
}
  • Related