2015-04-01 38 views
0

我所要做的就是看用户输入$ month是否在数组$ month中。但它不喜欢什么。帮帮我?- 包含运算符不工作powershell

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

回答

3

您测试逻辑仅仅是不好的一个,只是扭转youy测试或反向您的行为:

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

而不是使用-Contains你应该只使用-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的位置,然后询问一个月,如果它不是一个匹配,再次请求它,直到它与一个While。

$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" 
} 
+0

那么,这是工作,测试不是好的? – JPBlanc 2015-04-01 03:25:16

+0

@JPBlanc它的工作原理是,如果他做得对,是的,但是他不会遇到大小写敏感问题?或者 - 是否包含大小写不敏感? – TheMadTechnician 2015-04-01 03:41:27

+0

'CContains'区分大小写,而不是'Contains'。 – JPBlanc 2015-04-01 03:44:50