CASE、IFElse 或 SWITCH Powershell 以更改 Get-WmiObject 的输出

CASE, IFElse, or SWITCH Powershell to change output of Get-WmiObject

我有以下代码作为独立查询使用:

$Type = (Invoke-Command -ComputerName $Computer -ScriptBlock { Get-WmiObject -Class Win32_ComputerSystem  | Select-Object -ExpandProperty Manufacturer })

    switch -regex ($Type) 
    { 
        "VMw.+" {"VM"} 
        default {"Physical"}
    }

我想在 Invoke 命令中添加 switch 命令而不是变量(删除 $Type 变量),以便它可以 运行 针对多台计算机,这如何实现,我不是确定要使用 Switch 来完成最终结果?

Get-WmiObject 有一个 ComputerName 属性 所以你不需要使用 Invoke-Command

switch -regex (Get-WmiObject -ComputerName $Computer -Class Win32_ComputerSystem  | Select-Object -ExpandProperty Manufacturer)
{ 
    "VMw.+" {"VM"} 
    default {"Physical"}
}

通过将它包装在一个简单的 foreach 循环中,您可以轻松地 运行 它针对多台计算机:

$Computers = "computer1","computer3","computer3"

foreach ($Computer in $Computers) {
    switch -regex (Get-WmiObject -ComputerName $Computer -Class Win32_ComputerSystem  | Select-Object -ExpandProperty Manufacturer)
    { 
        "VMw.+" {Write-Output "$Computer is a VM Computer"} 
        default {Write-Output "$Computer is a Physical Computer"}
    }
}