-Contains运算符不工作powershell

时间:2015-04-01 03:08:15

标签: powershell

我尝试做的只是查看用户输入$ month是否在数组$ month中。但它并不喜欢什么。帮助

Write-host "The script is to collect from the user High Tempature and Low Tempature for a day in degrees F."
$months = @("January", "February","March","April","May","June","July","August","September","October","November","December")
$finished = $false
while ($finished -eq $false){
    $month = read-host "Enter the month";
    if ($months -Contains $month)
    {
        write-host "Invalid entry"
        $finished = $false
    }
    else
    {
        $finished = $true
    }
}

2 个答案:

答案 0 :(得分:3)

您测试逻辑不是好的,只需反转您的测试或反转您的操作:

Write-host "The script is to collect from the user High Tempature and Low Tempature for a day in degrees F."
$months = @("January", "February","March","April","May","June","July","August","September","October","November","December")
$finished = $false
while ($finished -eq $false){
    $month = read-host "Enter the month";
    if ($months -Contains $month)
    {
        $finished = $true
    }
    else
    {
        write-host "Invalid entry"
        $finished = $false
    }
}

答案 1 :(得分:0)

您应该使用-Contains运算符运行RegEx匹配,而不是使用-Match。或者,正如您目前正在测试否定结果,请改用-notmatch。您可以使用现有代码,只需通过使用竖线字符加入您的月份来稍微修改它。像:

Write-host "The script is to collect from the user High Tempature and Low Tempature for a day in degrees F."
$months = @("January", "February","March","April","May","June","July","August","September","October","November","December")
$finished = $false
while ($finished -eq $false){
    $month = read-host "Enter the month";
    if ($month -notmatch ($months -join "|"))
    {
        write-host "Invalid entry"


     $finished = $false
    }
    else
    {
        $finished = $true
    }
}

更好的是,让我们摆脱If / Else并缩短它。将加入移动到我们定义$Months的位置,然后询问一个月,如果不匹配,请再次询问它,直到它有一段时间。

$months = @("January", "February","March","April","May","June","July","August","September","October","November","December") -join '|'
$month = read-host "Enter the month"
While($month -notmatch $months){
    "Invalid Entry"
    $month = read-host "Enter the month"
}