在Format-Table表达式中使用哈希映射

时间:2012-01-12 01:08:10

标签: powershell

我试图从TechNet上的Use Windows PowerShell to Manage Virtual Machines文章中获取以下示例:

$VMState = @{
    2="Running"
    3="Stopped"
    32768="Paused"
    32769="Suspended"
    32270="Starting"
    32771="Snapshotting"
    32773="Saving"
    32774="Stopping"
}

$vms = get-wmiobject -computername localhost -Namespace root\Virtualization -query "Select * from MSVM_Computersystem where Description like '%Virtual%' "
$vms | format-table -autosize @{Label=”VM Name”; expression = {$_.elementName}}, Description, @{Label =”VM State”; expression = {$VmState[$_.EnabledState]}}

出于某种原因,我没有正确映射启用状态,也没有得到任何结果,如下所示:

VM Name Description               VM State
------- -----------               --------
SANS    Microsoft Virtual Machine         
SERIF   Microsoft Virtual Machine      

为什么这部分不起作用?

expression = {$VmState[$_.EnabledState]}

1 个答案:

答案 0 :(得分:2)

将哈希表更改为以下内容并尝试:

$VMState = @{
    "2"="Running"
    "3"="Stopped"
    "32768"="Paused"
    "32769"="Suspended"
    "32270"="Starting"
    "32771"="Snapshotting"
    "32773"="Saving"
    "32774"="Stopping"
}

替代方案是确保$_.EnabledState为int - [int]$_.EnabledState

请注意

$a="2"
$VMState[$a] #gives nothing
$a=2
$VMState[$a] #gives Running