【问题标题】:CASE, IFElse, or SWITCH Powershell to change output of Get-WmiObjectCASE、IFElse 或 SWITCH Powershell 更改 Get-WmiObject 的输出
【发布时间】:2016-12-01 12:50:57
【问题描述】:

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

$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来完成最终结果?

【问题讨论】:

    标签: powershell if-statement switch-statement case invoke


    【解决方案1】:

    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"}
        }
    }
    

    【讨论】:

    • 这对我有用:code"Type" = switch -regex (Get-WmiObject -ComputerName $Computer -Class Win32_ComputerSystem | Select-Object -ExpandProperty Manufacturer) { "VMw.+" {Write -输出“VM”}默认{写入输出“物理”}}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    相关资源
    最近更新 更多