Replacing XML node value using *.xml wildcard in powershell

This topic contains 2 replies, has 2 voices, and was last updated by  omer shahnewaz 2 years, 3 months ago.

  • Author
    Posts
  • #28899

    omer shahnewaz
    Participant

    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]($_|Get-Content) }}
    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 🙂

  • #28902

    Dave Wyatt
    Moderator

    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.

  • #28904

    omer shahnewaz
    Participant

    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.