如何在 PowerShell 中的函数结束时返回用户菜单 [英] How to return to user menu at the end of a function in PowerShell
问题描述
我正在编写一个 PowerShell 脚本,它为用户提供了许多可供选择的选项.一旦选择了一个选项,就会执行一个功能,用户将返回到原始菜单.
I am writing a PowerShell script that gives the user a number of options to select from. Once an option is selected, a function is executed and the user is returned back to the original menu.
在下面的代码中,为用户提供了选项,并执行了函数,但完成后,脚本就结束了.我想要的是在函数结束时返回原始用户菜单.有人能告诉我怎么做吗?谢谢!
In the code below, the user is given the options, and the functions are executed, but when complete, the script just ends. What I want instead is at the end of the function to return to the original user menu. Can someone tell me how to do this? Thanks!
function firstFunction {
Write-Host "You chose option 1"
return
}
Write-Host "Welcome"
[int]$userMenuChoice = 0
while ( $userMenuChoice -lt 1 -or $userMenuChoice -gt 4){
Write-Host "1. Menu Option 1"
Write-Host "2. Menu Option 2"
Write-Host "3. Menu Option 3"
Write-Host "4. Quit and Exit"
[int]$userMenuChoice = Read-Host "Please choose an option"}
switch ($userMenuChoice) {
1{firstFunction}
2{Write-Host "You chose option 2"}
3{Write-Host "You chose option 3"}
default {Write-Host "Nothing selected"}
}
推荐答案
将菜单代码放入一个外部循环中,除非 $userMenuChoice
为 4,否则不会终止:
Put the menu code into an outer loop that doesn't terminate unless $userMenuChoice
is 4:
do {
[int]$userMenuChoice = 0
while ( $userMenuChoice -lt 1 -or $userMenuChoice -gt 4) {
Write-Host "1. Menu Option 1"
Write-Host "2. Menu Option 2"
Write-Host "3. Menu Option 3"
Write-Host "4. Quit and Exit"
[int]$userMenuChoice = Read-Host "Please choose an option"
switch ($userMenuChoice) {
1{firstFunction}
2{Write-Host "You chose option 2"}
3{Write-Host "You chose option 3"}
default {Write-Host "Nothing selected"}
}
}
} while ( $userMenuChoice -ne 4 )
这篇关于如何在 PowerShell 中的函数结束时返回用户菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!