【问题标题】:Unable to use logical operator while comparing strings for input validation in Powershell在 Powershell 中比较字符串以进行输入验证时无法使用逻辑运算符
【发布时间】:2021-09-12 17:40:50
【问题描述】:

我正在尝试提示用户输入,然后验证用户输入是否匹配两个不同选项之一,如果没有给出正确的输入,我将退出。

在示例中,我要求用户输入“BOB”或“TOM”作为有效输入,但是当我运行此代码时,我总是会收到消息“未正确输入服务器类型”,即使我输入 BOB 作为提示的输入。

$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'

If ($ServerType -ne  "BOB" -Or $ServerType -ne  "TOM")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}

我也试过

If (($ServerType -ne  "BOB") -or ($ServerType -ne  "TOM"))
{
Write-Host -NoNewLine 'Server type not entered correctly'
}

但是,当我只测试一个值时,它会起作用:

If ($ServerType -ne  "BOB")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}

任何想法为什么我可能会得到这个?

【问题讨论】:

  • 在这种情况下您应该使用的运算符应该是-and$true OR $false = $true 这就是为什么你总是进入那个条件。

标签: windows powershell logical-operators


【解决方案1】:

在我的评论中,这种情况下的逻辑运算符应该是-and,但请允许我给您举两个可以改进验证的示例。

$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'

if($ServerType -notmatch '^(bob|tom)$')
{
    Write-Host -NoNewLine 'Server type not entered correctly'
}
try
{
    [validateset('bob','tom')]
    $ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
}
catch
{
    Write-Host -NoNewLine 'Server type not entered correctly'
}

【讨论】:

  • 谢谢!太好了,我从来不知道 -match/-notmatch 运算符。此外,ValidateSet 属性非常适合我的使用,也是我从未见过的。
  • @Bajan 很乐意为您提供帮助,也很高兴您正在学习新的东西 :) [validateset(...)] 可能是更高级的东西,您通常会在高级功能中看到它,但您也可以看到它对于这个测试用例。
猜你喜欢
  • 2014-04-07
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
相关资源
最近更新 更多