Replacing XML node value using *.xml wildcard in powershell

Hi,

I have a folder with 400+ xml files, I am trying to change the value of multiple nodes in all of them using a powershell script, I cant figure out how to save the files once they are edited, below is what i did so far

Get-ChildItem D:\source*.xml |%{{$filepath = $_.FullName;xml }}
ForEach-Object {$xml.fa.fb.fc =“1234”}
ForEach-Object {$xml.fa.fb.fd =“1234”}
ForEach-Object {$xml.fa.fb.fe =“1234”}

$xml.save("$filepath = $_.FullName") this line of code isn’t saving any of the .xml files, no error message in ISE, but error in powershell:
You cannot call a method on a null-valued expression.
At line:1 char:1

  • $xml.save("$filepath = $_.FullName")

I have executed the following to test how much of the codes are effective by

$xml.Save(“D:\source\d.xml”)
$xml.Save(“D:\source\a.xml”)
$xml.Save(“D:\source\b.xml”)

and the new values are saved in all the files except c.xml, d.xml etc.
any help would be appreciated :slight_smile:

You haven’t assigned anything to a variable called XML. In the code, you’ve been working with a pipeline with multiple ForEach-Object calls, which is probably not what you want. Try it like this:

Get-ChildItem D:\source\*.xml |
ForEach-Object {
    $filepath = $_.FullName
    $xml = [xml](Get-Content -Path $filepath)
    $xml.fa.fb.fc ="1234"
    $xml.fa.fb.fd ="1234"
    $xml.fa.fb.fe ="1234"
    $xml.Save($filepath)
}

This way, there’s only a single ForEach-Object loop happening, and there’s a value assigned to the $xml variable inside that loop.

Thank you for replying. It worked like a charm and i got the idea too.