在 if 语句中组合多个条件

combine multiple conditions in if-statement

当您希望一组或另一组 2 个条件为真时,如何将 4 个条件链接在一起?

更准确地说,我想做的是:

如果用户已登录且操作系统版本为 Windows10

用户已登录且 LogonUI 进程未 运行

不要理会这些命令,它们在隔离时都能正常工作,我的问题是将它们链接在一起。

例如我有:

if (
        (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem).UserName`
        -and`
        (Get-WmiObject -Computer $poste -Class Win32_OperatingSystem).Version -like "*10*"
    )
    { echo do X }

工作正常。我想在相同的 if 中添加另一个条件块。我试过了,但没有用:

if (
        (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem).UserName`
        -and`
        (Get-WmiObject -Computer $poste -Class Win32_OperatingSystem).Version -like "*10*"`
        -or`
        (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem).UserName`
        -and -not`
        (Get-Process -ErrorAction SilentlyContinue -ComputerName $poste -name logonui)
    )
    { echo do X }

如何像这样链接多个 "blocks"?我知道我可以做两个不同的 IF,我让它工作了,但是没有办法将它们全部链接在一个 IF 中吗? (IF包含很多代码,我不想用两个IF复制它)

所以在尝试了一些东西之后,似乎有两种方法:

if (
        (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem).UserName`
        -and`
        (Get-WmiObject -Computer $poste -Class Win32_OperatingSystem).Version -like "*10*"`

    ) { echo do X }

    elseif (

        (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem).UserName`
        -and -not`
        (Get-Process -ErrorAction SilentlyContinue -ComputerName $poste -name logonui)

    )   { echo do X }

或使用 Ansgar Wiechers 的出色答案将其全部链接在一个 IF 中:

if (
        (      
        (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem).UserName`
        -and`
        (Get-WmiObject -Computer $poste -Class Win32_OperatingSystem).Version -like "*10*"`
        ) -or`
        (       
        (Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem).UserName`
        -and -not`
        (Get-Process -ErrorAction SilentlyContinue -ComputerName $poste -name logonui)`
        )

    ) { echo do X }

将每组条件放在括号中:

if ( (A -and B) -or (C -and D) ) {
    echo do X
}

如果第一个第二组条件必须为真(但不是两者都为真)使用-xor 而不是 -or:

if ( (A -and B) -xor (C -and D) ) {
    echo do X
}

用各自的表达式替换 A、B、C 和 D。

如果您想使您自己的答案中的代码更容易理解,您可以删除重复代码以使 if 语句更清晰。

将结果分配给变量并改用它们:

$UserName = Get-WmiObject –ComputerName $poste –Class Win32_ComputerSystem | select -ExpandProperty UserName
$WindowsVersion = Get-WmiObject -Computer $poste -Class Win32_OperatingSystem | select -ExpandProperty Version
$LogonuiProcess = Get-Process -name logonui -ComputerName $poste -ErrorAction SilentlyContinue

然后:

if (($UserName -and $WindowsVersion -like "*10*") -or ($UserName -and -not $LogonuiProcess)) {Write-Output "do X"}

或者

if ($UserName -and $WindowsVersion -like "*10*") {Write-Output "do X"}
elseif ($UserName -and -not $LogonuiProcess) {Write-Output "do Y"}