2015-04-01 55 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