我对Powershell Realm 还不是很陌生,并且在解决此问题方面有些困难。与执行此操作的其他代码相比,我的代码很简单,但是下面的代码无法正常工作,我无法弄清楚自己做错了什么。与下面的简单$ VMToolsList相比,我使用更长,更复杂的“Lists”从开始做几乎完全相同的事情。当我运行下面的代码时,wsIndex1和2都收到以下错误。对我缺少的内容有任何想法吗?
使用“2”参数调用“IndexOf”的异常:“值不能为null。
参数名称:数组
在C:\ Users \ xxxxxxxxxxx \ AppData \ Local \ Temp \ f2dfef29-9e86-4193-9c37-98b35015e97f.ps1:9 char:2
+ $ wsIndex1 = [Array]::IndexOf($ VMToolsxml.Descendants(“$ {Namespace} th”)。Value,...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:未指定:(:) [],MethodInvocationException
+ FullyQualifiedErrorId:ArgumentNullException
Add-Type -AssemblyName System.Xml.Linq
New-VIProperty -Name ToolsVersion -ObjectType VirtualMachine -ValueFromExtensionProperty 'Config.tools.ToolsVersion' -Force
New-VIProperty -Name ToolsVersionStatus -ObjectType VirtualMachine -ValueFromExtensionProperty 'Guest.ToolsVersionStatus' -Force
$VMToolsList = $(Get-VM | Select Name, Version, ToolsVersion, ToolsVersionStatus)
$VMToolsxml = [System.Xml.Linq.XDocument]::Parse( "$($VMToolsList | ConvertTo-Html)" )
$wsIndex1 = [Array]::IndexOf( $VMToolsxml.Descendants("${Namespace}th").Value, "Version")
$wsIndex2 = [Array]::IndexOf( $VMToolsxml.Descendants("${Namespace}th").Value, "ToolsVersionStatus")
foreach($row in $VMToolsxml.Descendants("${Namespace}tr")){
switch(@($row.Descendants("${Namespace}td"))[$wsIndex1]) {
{"v7" -eq $_.Value } { $_.SetAttributeValue( "style", "background: green;"); continue }
{"v7" -ne $_.Value } { $_.SetAttributeValue( "style", "background: red; font color: black"); continue }
}
switch(@($row.Descendants("${Namespace}td"))[$wsIndex2]) {
{"guestToolsCurrent" -eq $_.Value } { $_.SetAttributeValue( "style", "background: green;"); continue }
{"guestToolsNeedUpgrade" -eq $_.Value } { $_.SetAttributeValue( "style", "background: yellow; font color: black"); continue }
{"guestToolsNotInstalled" -eq $_.Value } { $_.SetAttributeValue( "style", "background: red; font color: black"); continue }
{"guestToolsUnmanaged" -eq $_.Value } { $_.SetAttributeValue( "style", "background: purple;"); continue }
}
}
最佳答案
首先调试为什么$VMToolsxml.Descendants("${Namespace}th").Value
导致为空。顺便说一句,XLinq和PowerShell不能很好地协同工作。后代是PowerShell不自动支持的扩展方法。您可以通过以下方式使用扩展方法:
[System.Xml.Linq.Extensions]::Descendants($VMToolsxml, "${Namespace}th")
我会考虑使用PowerShell对System.Xml.XmlDocument的支持,并将Select-Xml与XPath查询一起使用以查找您的节点。
关于xml - 为PowerShell脚本异常的结果添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498309/