1

I am working on a simple powershell script that verify if inside of the xml file the attribute(s) exists. The xml file looks like,

<?xml version="1.0"?>
 <Objects>
  <Object>
   <Property Name="Browser">Firefox</Property>
   <Property Name="PDF">Adobe Reader</Property>
 </Object>
</Objects>

I want the powershell to verify if the attribute Firefox exists, and then to execute a task afterward.

[xml]$file = get-content C:\Admin\personalsettings.xml
$xmlProperties = $file.SelectNodes("/Objects/Object/Property")
Foreach ($xmlProperty in $xmlProperties) {
$strName = ($xmlProperty | Where-Object {$_.Name -eq "Firefox"    }).InnerXml
 If ($strName -eq "False")
 {
 Invoke-Item "C:\windows\protected\browser.exe"
 }
}
js2010
  • 23,033
  • 6
  • 64
  • 66
user2843475
  • 13
  • 1
  • 6

2 Answers2

0

Note that Firefox is a child text node (the text content) of a Property element in your XML, accessible via the latter's .InnerText property.

Therefore, you can retrieve the / test the existence of a Property element of interest as follows, using the Where() array method:

$firefoxElem = $xmlProperties.Where({ $_.InnerText -eq 'FireFox' }, 'First')
$haveFirefoxElem = [bool] $firefoxElem

A simpler approach, if you only need to know the presence of the element of interest, is to use PowerShell's XML dot notation, which obviates the need for XPath expressions via .SelectNodes():

$haveFirefoxElem = $file.Objects.Object.Property.InnerText -contains 'FireFox'
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • @user2843475 With the information given, I cannot answer your question; note that nothing in your question relates to XML _attributes_, only to _elements_ and their _text content_. Please consider that the value of this site is in providing focused solutions to focused answers that _future readers_ can discover and benefit from _as well_. Having tangential conversations takes away from that. Please ask a new, focused question if you need further help. – mklement0 Feb 28 '20 at 14:08
0

Using xpath (case sensitive):

if (select-xml "/Objects/Object/Property[text()='Firefox']" file.xml) { 'yes' } 
if (select-xml "//Property[text()='Firefox']" file.xml) { 'yes' } 
if (select-xml "//*[Property='Firefox']" file.xml) { 'yes' }
if (select-xml "*[Object[Property[@Name='Browser']='Firefox']]" file.xml) { 'yes' }
js2010
  • 23,033
  • 6
  • 64
  • 66