0
<?xml version="1.0" encoding="utf-8"?>
<Test1>
  <Test1Properties>
    <Property1>replace this</Property1>
  </Test1Properties>
  <Test1Sources>
    <Source1>
      <SourceReference>sourceref</SourceReference>
      <SourceType>None</SourceType>
    </Source1>
    <Source2>
      <Source2Properties>
        <Provider>prov</Provider>
        <ProviderKey>some-guid</ProviderKey>
      </Source2Properties>
    </Source2>
  </Test1Sources>
</Test1>

Given the xml above, there are 3 tasks that I need to accomplish in Powershell:

  1. Replace the value of <Test1><TestProperties><Property1> with new-value
  2. Verify that <Test1><TestSources><Source1><SourceType> value = None
  3. How to determine if <Test1><Test1Sources><Source2><Source2Properties> exists within <Source2>

I'm assuming reading into an xml variable is the best way to start? Like:

[xml]$xmlAttr = Get-Content -Path TestFile.xml

I hardly use Powershell at all much less with XML, so hoping these are fairly straightforward asks. Thanks in advance.

1 Answer 1

2

The following are some examples of how to handle your XML data:

# Deserialize the XML text Option 1.
# This is syntactically simpler but is susceptible to encoding issues.
[xml]$xml = Get-Content -Path TestFile.xml

# Deserialize the XML text Option 2. Must use full path in Load method.
$xml = [xml]::new()
$xml.Load('C:\Temp\TestFile.xml')

# Update Node Property1 value
$xml.Test1.Test1Properties.Property1 = 'new value'

# Return True if SourceType node has value of None
$xml.Test1.Test1Sources.Source1.SourceType -ceq 'None'

# Return True if Source2Properties Exists as a child node of Source2
$xml.SelectSingleNode("//Test1/Test1Sources/Source2/Source2Properties") -is [System.Xml.XmlElement]

# Save results in your xml file. Must use a full path in Save() method.
$xml.Save('C:\temp\TestFile.xml')
Sign up to request clarification or add additional context in comments.

1 Comment

Everything needed in a concise, efficient, well-documented answer. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.