2

我对 Powershell 世界还很陌生,想弄清楚这个问题有点困难。我的代码在下面并且非常简单,与我做过的其他代码相比,但是这个代码不起作用,我不知道我做错了什么。与下面的简单 $VMToolsList 相比,我使用更长和更复杂的“列表”开始几乎完全相同的事情。当我运行下面的代码时,wsIndex1 和 2 都出现以下错误。知道我缺少什么吗?

使用“2”参数调用“IndexOf”的异常:“值不能为空。参数名称:数组”在 C:\Users\xxxxxxxxxxx\AppData\Local\Temp\f2dfef29-9e86-4193-9c37-98b35015e97f.ps1 :9 char:2 + $wsIndex1 = [Array]::IndexOf( $VMToolsxml.Descendants("${Namespace}th").Value, ... + ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], 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 }
    }
}
4

2 回答 2

1

首先调试为什么$VMToolsxml.Descendants("${Namespace}th").Value会导致空值。顺便说一句,XLinq 和 PowerShell 不能很好地协同工作。后代是 PowerShell 不自动支持的扩展方法。您可以这样使用扩展方法:

[System.Xml.Linq.Extensions]::Descendants($VMToolsxml, "${Namespace}th")

我会考虑使用 PowerShell 对 System.Xml.XmlDocument 的支持,并使用 Select-Xml 和 XPath 查询来查找您的节点。

于 2013-08-29T00:15:26.107 回答
0

在第 9 行中,您正在使用XContainer.Descendants Method (XName)。此方法返回一个似乎不支持 .Value 方法的IEnumerable 接口,这就是我怀疑它返回 null 的原因。

http://msdn.microsoft.com/en-us/library/bb360635.aspx

http://msdn.microsoft.com/en-us/library/9eekhta0.aspx

只是一个试图提供帮助的业余爱好者,希望这是在正确的轨道上。

于 2013-08-29T01:53:04.850 回答