Home > Net >  Config Update - PowerShell
Config Update - PowerShell

Time:11-23

hoping someone can point me in the right direction.

Background:

Environment is Windows 10 - I need to update a line within a config file for our users, from a numerical IP to a string. Each device this is being scoped to has the possibility of multiple configuration files within the defined path of the script with different previous user config files present. For this I’ve done the script as a wildcard to update all the located configs to have the same line updated so it’s uniform and avoids conflicts after deployment. Currently the script works to replace the values but when additional configurations are picked up by the script they are being combined and re-entered for each config found.

The script in its current form

((Get-Content -Path "C:\Program Files\ProgramX\config\brand-protocol-port-*-config.ext" -Raw) -replace 'X.X.X.X','VALUE') |
    Set-Content -Path " C:\Program Files\ProgramX\config\brand-protocol-port-*-config.ext "
Get-Content -Path " C:\Program Files\ProgramX\config\brand-protocol-port-*-config.ext "

The consequence is, if there is a config file for John Smith and John Walker - after the script is run the files are updated as intended but instead of 2 separate config files being updated, they are updated then added together in each instance with the updated files being present within each other.

Any pointers are appreciated!

CodePudding user response:

What you need is to use a loop so each file can be processed separately:

# since we're using the regex `-replace` operator, the dots need to be escaped
$ipToFind    = [regex]::Escape('X.X.X.X')
$replaceWith = 'VALUE'
Get-ChildItem -Path 'C:\Program Files\ProgramX\config' -Filter 'brand-protocol-port-*-config.ext' -File | ForEach-Object {
    (Get-Content -Path $_.FullName -Raw) -replace $ipToFind, $replaceWith | Set-Content -Path $_.FullName
}
  • Related