Ansgar Wiechers' helpful answer explains the problem with your code well and offers helpful background information.
Here's a concrete solution that shows some related techniques:
$file = [System.Runtime.InteropServices.RuntimeEnvironment]::SystemConfigurationFile
[xml] $xml = Get-Content -Raw $file
# Get the <oracle.manageddataaccess.client> element
# that, in this example, is assumed to be a child element of the
# top-level <configuration> element.
$elem = $xml.configuration.'oracle.manageddataaccess.client'
# Determine if the element exists.
$exists = $null -ne $elem
Explanation:
[xml] $xml = Get-Content -Raw $file
is a more PowerShell-idiomatic way of reading an XML document from a file; using the [xml]
type accelerator automatically turns the file's content, obtained with Get-Content
, into an XML document (System.Xml.XmlDocument
).
$xml.configuration.'oracle.manageddataaccess.client'
uses PowerShell's adaptation of the XML DOM to provide convenient access to the elements in the document hierarchy with dot notation (.
)
Note that this assumes that you know the precise location (path to) the target element; if you don't, use .SelectNodes()
or .SelectSingleNode()
as recommended in Ansgar's answer; see example at the bottom.
Note the need to enclose oracle.manageddataaccess.client
in '...'
(quotes), because the element name itself contains .
characters.
For more information about how PowerShell adapts the XML DOM, see this answer.
If the targeted element exists, a System.Xml.XmlElement
instances is returned, if the target element has child elements of its own (otherwise, its .InnerText
property would be returned).
If no such element exists, the return value is $null
.
$exists = $null -eq $elem
creates a Boolean variable that indicates whether the element of interest exists or not.
Example uses of .SelectSingleNode()
with XPath queries:
The following returns a <oracle.manageddataaccess.client>
element found anywhere in the document, if present, and $null
otherwise:
$xml.SelectSingleNode('//oracle.manageddataaccess.client')
The following locates a <section>
element that is a child element of elements <configuration>
and <configSections>
and that contains a name
attribute containing the string appSettings
$xml.SelectSingleNode('/configuration/configSections/section[@name="appSettings"]')