1

I've parsed the XML file and I have these strings. So, I need to replace the GUID "{87440A4C-1FE4-412E-80C3-74E4F97A31B4}" with a new GUID "{BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}". How can I save XML after these changes?

Strings which I parsed:

C:\ProgramData\Program {87440A4C-1FE4-412E-80C3-74E4F97A31B4}\Extensions\Signal Integrity  
C:\ProgramData\Program {87440A4C-1FE4-412E-80C3-74E4F97A31B4}\Extensions\Vcs_SVN_Unicode 
C:\ProgramData\Program {87440A4C-1FE4-412E-80C3-74E4F97A31B4}\Extensions\Mixed Simulation 
C:\ProgramData\Program {87440A4C-1FE4-412E-80C3-74E4F97A31B4}\Extensions\SIMetrix
$fileName = "C:\temp\Extensions\ExtensionsRegistry.xml"
$xml = [System.Xml.XmlDocument](Get-Content $fileName)

$Xml.Extensions.Item.Path.ForEach{ $_ -replace 'Program  {87440A4C-1FE4-412E-80C3-74E4F97A31B4}', "Program {BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}"}

$Xml.Save($fileName)
zagnafey
  • 89
  • 1
  • 6
  • `$yourStringArray -replace '{87440A4C-1FE4-412E-80C3-74E4F97A31B4}', '{BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}'` – zett42 Jan 19 '21 at 22:22
  • yes, I made this variant. But how to save the results in xml file after those changes? – zagnafey Jan 19 '21 at 22:26
  • $XmlDocument.Extensions.Item.Path.ForEach{ $_ -replace 'Program {87440A4C-1FE4-412E-80C3-74E4F97A31B4}', "Program {BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}"} How to apply these changes in xml file? – zagnafey Jan 19 '21 at 22:33

2 Answers2

2
  • The -replace operator doesn't modify its LHS in place, it returns a modified copy of the LHS.

  • If the Path elements only have text content, using PowerShell's adaptation of the XML via dot notation returns just that text itself, not the element objects, so you cannot modify the elements that way.

Therefore, you must enumerate the Path elements differently and assign the result of the
-replace operations back to their .InnerText property:

$xml.Extensions.Item.ChildNodes.Where({ $_.Name -eq 'Path' }).ForEach({ 
  $_.InnerText = $_.InnerText -replace 'Program  {87440A4C-1FE4-412E-80C3-74E4F97A31B4}', 'Program {BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}'
})
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Pipe the output to a file, via Set-Content.

Dan
  • 106
  • 4
  • after Set-Content only parsed strings save in file – zagnafey Jan 19 '21 at 22:54
  • 1
    Maybe instead of converting the file contents to XML just do a simple text replace. (gc -raw 'C:\temp\Extensions\ExtensionsRegistry.xml') -replace 'Program {87440A4C-1FE4-412E-80C3-74E4F97A31B4}', 'Program {BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}' | sc -path 'C:\temp\Extensions\ExtensionsRegistry.xml' -force -verbose – Dan Jan 19 '21 at 23:03
  • Thanks, but I have to do it with powershell – zagnafey Jan 19 '21 at 23:11