簡體   English   中英

為PowerShell腳本異常添加顏色

[英]Adding color to results of PowerShell scripts Exception

我對Powershell領域還很陌生,在弄清楚這個問題方面有些困難。 與執行此操作的其他代碼相比,我的代碼非常簡單,但是此代碼將無法正常工作,而且我無法弄清楚自己做錯了什么。 與下面的簡單$ VMToolsList相比,我使用更長,更復雜的“ Lists”從開始做幾乎完全相同的事情。 當我運行下面的代碼時,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:未指定:(:) [],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導致空值。 BTW XLinq和PowerShell不能很好地協同工作。 后代是PowerShell不自動支持的擴展方法。 您可以通過以下方式使用擴展方法:

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

我會考慮使用PowerShell對System.Xml.XmlDocument的支持,並將Select-Xml與XPath查詢一起使用以查找您的節點。

在第9行中,您正在使用XContainer.Descendants方法(XName) 此方法返回一個IEnumerable接口 ,該接口似乎不支持.Value方法,這就是為什么我懷疑它返回null的原因。

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

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

只是一個試圖提供幫助的業余愛好者,希望這是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM