我需要幫助才能正確回傳我的輸入。當用戶點擊“1”時,它應該說“你好,人!” 當用戶點擊“2”時,它應該說“再見人!” 無論我改變什么,我似乎只能得到第二個選項。我包括了代碼,以及代碼的螢屏截圖。對于能夠幫助我解決此問題的任何人,我將不勝感激。
$title = "Convert Bat to Ps1"
$message = "Press 1 to say Hello, or Press 2 to say Goodbye"
$option1 = New-Object System.Management.Automation.Host.ChoiceDescription "1", "1"
$option2 = New-Object System.Management.Automation.Host.ChoiceDescription "2", "2"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($option1, $option2)
$choice=$host.ui.PromptForChoice($title, $message, $options, 1)
If ($option1 -eq 1) {
'Hello, Person!'
exit
}
If ($option2 -ne 2) {
'Goodbye, Person!'
exit
}
帶有我遇到問題的代碼的影像
uj5u.com熱心網友回復:
提示選擇的結果將存盤在 中$choice,而不是存盤在$Option1或 中$Option2。
回傳的值PromptForChoice將為零索引,因此要測驗選項 1:
if($choice -eq 0){
"Option 1 was chosen"
}
if($choice -eq 1){
"Option 2 was chosen"
}
uj5u.com熱心網友回復:
您不應該檢查 variable$option1或$option2,而是測驗 variable 的值$choice,因為這會告訴您單擊了哪個按鈕。
另外,下面我使用 aswitch而不是 multiple if\else:
$title = "Convert Bat to Ps1"
$message = "Press 1 to say Hello, or Press 2 to say Goodbye"
$option1 = New-Object System.Management.Automation.Host.ChoiceDescription "1", "Option 1"
$option2 = New-Object System.Management.Automation.Host.ChoiceDescription "2", "Option 2"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($option1, $option2)
$choice = $host.ui.PromptForChoice($title, $message, $options, 1)
# $choice is now an Int32 value, it's the Index of the button that is clicked:
# 0 for option 1 and 1 for option 2
switch ($choice) {
0 { 'Hello, Person!' } # left out the exit here so you can stay in your PowerShell instance
1 { 'Goodbye, Person!'; exit }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316340.html
