[英]PowerShell XML - Get value from node depending on another nodes value
[英]Powershell to get text nodes from xml
我正在編寫一個簡單的 powershell 腳本,用於驗證 xml 文件中的屬性是否存在。 xml文件看起來像,
<?xml version="1.0"?>
<Objects>
<Object>
<Property Name="Browser">Firefox</Property>
<Property Name="PDF">Adobe Reader</Property>
</Object>
</Objects>
我希望 powershell 驗證屬性 Firefox 是否存在,然后執行任務。
[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"
}
}
請注意, Firefox
是 XML 中Property
元素的子文本節點(文本內容),可通過后者的.InnerText
屬性訪問。
因此,您可以使用Where()
數組方法檢索 / 測試感興趣的Property
元素的存在,如下所示:
$firefoxElem = $xmlProperties.Where({ $_.InnerText -eq 'FireFox' }, 'First')
$haveFirefoxElem = [bool] $firefoxElem
一種更簡單的方法,如果您只需要知道感興趣的元素的存在,是使用PowerShell 的 XML 點表示法,它不需要通過.SelectNodes()
使用 XPath 表達式:
$haveFirefoxElem = $file.Objects.Object.Property.InnerText -contains 'FireFox'
使用 xpath(區分大小寫):
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' }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.