powershell比较字符串与-or

时间:2016-06-24 11:14:03

标签: powershell

我试图验证变量的值,但不管怎样,如果不使用-or

,我只能得到正确的结果
if (!$SER -eq "Y" -or  !$SER -eq "N"){
    write-host "ERROR: Wrong value for services restart" -foreground "red"
}

或者像这样

if (-not($SER -eq "Y") -or  -not($SER -eq "N")){
    write-host "ERROR: Wrong value for services restart" -foreground "red"
}

2 个答案:

答案 0 :(得分:2)

这有效(ne代表不等于):

if ($SER -ne "Y" -or $SER -ne "N") {
    Write-Host "ERROR: Wrong value for services restart" -ForegroundColor Red
}

这也有效:

if ("Y", "N" -notcontains $SER) {
    Write-Host "ERROR: Wrong value for services restart" -ForegroundColor Red
}

自PowerShell v3开始:

if ($SER -notin "Y", "N") {
    Write-Host "ERROR: Wrong value for services restart" -ForegroundColor Red
}

about_Comparison_Operators (v3)

答案 1 :(得分:0)

sodawillow provided a valid answer。但是,您可以使用-notin

来简化此操作
if ($SER -notin 'Y', 'N') {
    Write-Host "ERROR: Wrong value for services restart" -ForegroundColor Red
}