Retrieving an attribute value from XPath of an XML using powershell

advertisements

I am having an issue with getting and setting attribute value from XPath of an XML Config File using powershell. Attributes are like

"<add key="TransactDeadLetterQueueThreshold" value="0" />".

Sample XML File :

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <appSettings>
        <add key="ReportFile" value="C:\Program Files\Fusion\Viewer Suite Monitoring\ViewersMonitoring\monitor.txt" />
    <add key="QueueThreshold" value="1000" />
    <add key="TransactDeadLetterQueueThreshold" value="0" />
    <add key="TimeCardsThreshold" value="6000" />
    <add key="PercentDiskSpaceThreshold" value="10" />
    <add key="QueueCreatedFormat" value="The {0} queue is created." />
    <add key="QueueOverThresholdFormat" value="The {0} queue size is larger than {1} messages." />
    <add key="QueueTransactDeadLetterOverThresholdFormat" value="The transactional dead queue size is larger than {0} messages." />
    <add key="DriveThresholdFormat" value="The {0} drive space is less than {1}." />
    <add key="QueueRemovedFormat" value="The {0} queue is removed." />
    <add key="TimeCardsOverThresholdFormat" value="The time card records count is greater than or equal to {0} ." />
    <add key="FailedConnectDbFormat" value="Failed: unable to access the database, reason: {0}" />
    <add key="LogName" value="Viewer Suite Monitor" />
    <add key="ViewersPrivateQueues" value="private$\adt,private$\infusionviewer,private$\timecards" />
    <add key="DrivetobeMonitored" value="D:" />
  </appSettings>

I tried to grab the attribute the following way :

$xdoc = Get-content "C:\Program Files\Fusion\Viewer Suite Monitoring\CareFusion.Infusion.ViewerSuite.Monitoring.exe.config"

$value = ($xdoc.configuration.appSettings.SelectSingleNode(add[@key = "PercentDiskSpaceThreshold"])) + $value.GetAttribute('key')

and also tried this way :

$xdoc = Get-Content "C:\Program Files\Fusion\Viewer Suite Monitoring\Fusion.ViewerSuite.Monitoring.exe.config"
$value = $xdoc.selectSingleNode("/configuration/appSettings/add[@key = ""TransactDeadLetterQueueThreshold""] ")'+"
$value.GetAttribute('key')"

I am getting errors. I do not know what is wrong with this. Please help.


Here's an alternative which relies more on PowerShell and less on the .NET XML API:

# Get the attribute value
$xdoc = [xml](Get-Content <path-to-xml-file>)
$key = $xml.configuration.appsettings.add | Where {$_.Key -eq 'TransactDeadLetterQueueThreshold'}
$key.Value

# Set the attribute
$key.Value = '1'

You still need to use $xdoc.Save(<path>) to save the changes to file.