xmlpowershellselectsinglenode

PowerShell, how to select an xml node


I cannot select the FirstLogonCommands node. Why does $firstLogonCommands always come back as null and how can the FirstLogonCommands section be properly selected?

# Load the XML content
$xml = @"
<unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
  <settings pass="offlineServicing">
  </settings>
  <settings pass="windowsPE">
    <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
      <SetupUILanguage>
        <UILanguage>en-US</UILanguage>
      </SetupUILanguage>
      <InputLocale>0809:00000809</InputLocale>
      <SystemLocale>en-GB</SystemLocale>
      <UILanguage>en-US</UILanguage>
      <UserLocale>en-GB</UserLocale>
    </component>
  </settings>
  <settings pass="oobeSystem">
    <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
      <InputLocale>0809:00000809</InputLocale>
    </component>
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
      <FirstLogonCommands>
        <!-- Content here -->
      </FirstLogonCommands>
    </component>
  </settings>
</unattend>
"@

# Create an XML document object
$xmlDocument = New-Object System.Xml.XmlDocument
$xmlDocument.LoadXml($xml)

# Select the FirstLogonCommands node
$firstLogonCommands = $xmlDocument.DocumentElement.SelectSingleNode('//settings[@pass="oobeSystem"]/component[@name="Microsoft-Windows-Shell-Setup"]/FirstLogonCommands')

# Check if the FirstLogonCommands node exists
if ($firstLogonCommands -eq $null) {
    Write-Output "FirstLogonCommands section not found under 'Microsoft-Windows-Shell-Setup' component in the 'oobeSystem' settings pass."
} else {
    Write-Output "FirstLogonCommands section found:"
    Write-Output $firstLogonCommands.InnerXml
}

Solution

  • You just need to include the dns for each item in the path:

    $ns = @{dns="urn:schemas-microsoft-com:unattend"}
    Select-Xml -Xml $xmlDocument -XPath '//dns:settings[@pass="oobeSystem"]/dns:component[@name="Microsoft-Windows-Shell-Setup"]/dns:FirstLogonCommands' -Namespace $ns