Replacing XML node value using *.xml wildcard in powershell

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of omer shahnewaz omer shahnewaz 1 year, 2 months ago.

  • Author
  • #28899
    Profile photo of omer shahnewaz
    omer shahnewaz


    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]($_|Get-Content) }}
    ForEach-Object {$xml.fa.fb.fc ="1234"}
    ForEach-Object {$xml.fa.fb.fd ="1234"}
    ForEach-Object {$xml.fa.fb.fe ="1234"}

    $"$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
    + $"$filepath = $_.FullName")

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


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

  • #28902
    Profile photo of Dave Wyatt
    Dave Wyatt

    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"

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

  • #28904
    Profile photo of omer shahnewaz
    omer shahnewaz

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

You must be logged in to reply to this topic.