0

I'm basing my script off of this post. I don't know if some of the characters Im trying to replace from/to are causing an issue but I thought ive escaped everything required.

#Get file to replace 1 line in
$preferenceFile = 'C:\ProgramData\Redshift\preferences.xml'

# Get line object in file that contains the string "CacheFolder"
$line = Get-Content $preferenceFile | Select-String CacheFolder | Select-Object -ExpandProperty Line

#Load the file
$content = Get-Content $preferenceFile

# Feed the file contents into the replacement machine and set the file contents
$content | ForEach-Object {$_ -replace $line,"`t<preference name=`"CacheFolder`" type=`"string`" value=`"NONSENSE`" />"} | Set-Content $preferenceFile

I also tried this line where <TAB> is an actual tab character rather than the `t:

$content | ForEach-Object {$_ -replace $line,'<TAB><preference name="CacheFolder" type="string" value="NONSENSE" />'} | Set-Content $preferenceFile
bluesquare
  • 109
  • 3
  • 4
    Could you share an example of how your XML looks like and your desired result? Also, if it's actually an XML, you likely want to use `XMLDocument` to update it. – Santiago Squarzon Feb 01 '22 at 23:49

1 Answers1

0

you just need to use this to replace a word:

$preferenceFile = 'C:\ProgramData\Redshift\preferences.xml'
(Get-Content $preferenceFile).replace('CacheFolder', 'NONSENSE') | Set-Content $preferenceFile 

enter image description here

If you want to replace the entire line that contains a word then use this:

$preferenceFile = 'C:\Users\Clint.Oliveira\Desktop\preferences.xml'
$hold = @()
foreach($line in Get-Content $preferenceFile) {
    if($line -match 'CacheFolder'){
        $hold = $line -replace $line, 'NONSENSE '
        $Out += $hold
    }
    else{$Out += $line}
}
$Out | Set-Content $preferenceFile  -Force

enter image description here

Clint Oliveira
  • 647
  • 3
  • 8