Home > Mobile >  Attempting to search and replace a few lines in an XML file in every user's appdata/roaming fol
Attempting to search and replace a few lines in an XML file in every user's appdata/roaming fol

Time:03-22

I'm still kind of new to windows administration and very new to powershell so please forgive my ignorance. I wrote the following one-liner and I'm attempting to adapt it so that it can modify every existing user's FTRSettings.xml file on a PC. I'm worried that using the following path with a wildcard in place of the username would only replace the first file it finds.

C:\users\*\appdata\Roaming\FTR\GoldMain\FTRSettings.xml

Tested and working one liner executed from the appdata\Roaming\FTR\GoldMain\ directory.

((Get-Content -Path .\FTRSettings.xml -Raw) -replace '<Setting name="audioLevelsVisible" type="11">0</Setting>','<Setting name="audioLevelsVisible" type="11">-1</Setting>' -replace '<Setting name="inputLevelsVisible" type="11">0</Setting>','<Setting name="inputLevelsVisible" type="11">-1</Setting>' -replace '<Setting name="logSheetPaneViewState" type="11">0</Setting>','<Setting name="logSheetPaneViewState" type="11">-1</Setting>')

I was wondering if anyone could point me in the right direction.

CodePudding user response:

To process each file individually:

  • Use Get-ChildItem with your wildcard-based path to find all matching files.

  • Loop over all matching files with ForEach-Object and perform the string replacement and updating for each file.

Note: I'm using a single -replace operation for brevity.

Get-ChildItem -Path C:\users\*\appdata\Roaming\FTR\GoldMain\FTRSettings.xml | 
  ForEach-Object {
    $file = $_
    ($file | Get-Content -Raw) -replace 'foo', 'bar' |
      Set-Content -Encoding utf8 -LiteralPath $file.FullName -WhatIf
  }

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

Note the use of -Encoding to control the character encoding explicitly, because the original encoding is never preserved in PowerShell; instead, the cmdlet's own default applies - adjust as needed.

  • Related