Read from the XML file using Powershell

advertisements

I'm finding it hard to figure out a way to retrieve content from XML file. Below is how my xml file looks like. I'm trying to retrieve the complete 'nlog' node. Please help.

<configuration>
<configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, ..."/>
 </configSections>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <variable name="LoggingDirectory" value="D:/Logging/"/>
      <include file="${LoggingDirectory}Config/Framework.nlog.xml"/>
  </nlog>
 </configuration>

here is what I have tried so far:

$nlogConfigFile = 'D:\machine.config.nlog.xml'
$nlogConfigXml = new-object xml
$nlogConfigXml.Load($nlogConfigFile);
$nlogConfigXml.PreserveWhitespace = $true

I have used the "Get-XmlNode" function provided in this blog http://blog.danskingdom.com/powershell-functions-to-get-an-xml-node-and-get-and-set-an-xml-elements-value-even-when-the-element-does-not-already-exist/

Get-XmlNode -XmlDocument $nlogConfigXml -NodePath "configuration.configSections.section[@name='nlog']"     ## works OK
Get-XmlNode -XmlDocument $nlogConfigXml -NodePath "configuration.nlog"   ## does NOT work

I have also tried "Select-Xml" , .SelectSingleNode commands but none of them seem to work. Please let me know if I'm missing something.


This works:

$nlogConfigXml = [xml]$(gc "D:\machine.config.nlog.xml")

Then you can navigate $nlogConfigXml using object notation.

For example, doing this:

$nlogConfigXml.configuration.nlog.variable.name

...outputs this:

LoggingDirectory