powershell - 跳转到 PowerShell 脚本中的另一部分

标签 powershell

我想从脚本中的一个部分跳转到同一个 PowerShell 脚本中的另一部分。我的脚本现在只是从上到下,但我有几个任务。例如我希望能够从脚本开头的任务列表中进行选择,然后转到任务编号 2 跳过任务 1。

我希望这对你有意义。看看我的脚本:

Write-Host -ForegroundColor Yellow "welcome to my powershell script..."
""
""
""
Start-Sleep -Seconds 1
Write-Host -ForegroundColor Yellow "Choose a task:"
""
""

Write-Host -ForegroundColor Yellow "1. Clean up"
Write-Host -ForegroundColor Yellow "2. Uninstall Pre-Installed Apps" 
Write-Host -ForegroundColor Yellow "3. Something should be written here"
""
""
""

While ($Valg -ne "1" -or $Valg -ne "2" -or $Valg -ne "3") {

    $Valg = Read-Host "Choose a number from the task list"

    If ($Valg –eq "1") { Break }
    If ($Valg –eq "2") { Break }
    If ($Valg –eq "3") { Break }

    if ($Valg -ne "1" -or $Valg -ne "2" -or $Valg -ne "3") {
        ""
        Write-Host -ForegroundColor Red "Ups. Try again..."
    }
}

#### 1. First task should come here (clean up)
#some code here for the "cleaning up" task 

#### 2. Second task here
#some code here for the "Uninstall Pre-Installed Apps" task

#### 3. Third task there
#Some code for the third task here

#### And so on...

最佳答案

这是一个使用 array 的通用解决方案的 PSCustomObject表示任务(消息和要调用的函数)。它不需要开关,您可以简单地将新任务添加到数组中(并实现所需的功能),而无需修改剩余的脚本:

# define a task list with the messages to display and the functions to invoke:
$taskList = @(
    [PSCustomObject]@{Message = 'Clean up'; Task = { Cleanup }}
    [PSCustomObject]@{Message = 'Uninstall Pre-Installed Apps'; Task = { Uninstall }}
    [PSCustomObject]@{Message = 'Something should be written here'; Task = { Print }}   
)

# define the functions:
function Cleanup()
{
    Write-Host "Cleanup"
}

function Uninstall()
{
    Write-Host "Uninstall"
}

function Print()
{
    Write-Host "Print"
}


# let the user pick a task:
Write-Host -ForegroundColor Yellow "Choose a task:"

$taskList | foreach -Begin { $i = 1;} -Process { 
    Write-Host -ForegroundColor Yellow ('{0}. {1}' -f ($i++), $_.Message) 
}

do 
{
    $value = Read-Host 'Choose a number from the task list'

}
while($value -match '\D+' -or $value -le 0 -or $value -gt $taskList.Count)

# invoke the task:
& $taskList[$value-1].Task

关于powershell - 跳转到 PowerShell 脚本中的另一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36798888/

相关文章:

powershell - 如何在 PowerShell 中获取当前文件位置

windows - 如何在此PowerShell代码中添加异常处理?

python - Awk 比较 3 个值,第一个文件值之间的第二个文件值,两个文件之间的多列打印输出到第三个

powershell - 从字节转换为千兆字节

powershell - 以 UTF8 保存时,如何在保留现有换行符的同时防止使用 set-content 额外换行符?

powershell - Azure 自动化 - 每天自动重新启动一次 Web 应用程序的 Runbook

powershell - 将变量传递给函数会创建一个数组

powershell - 如何使用属性和方法创建[PsCustomObject]

powershell - 读主机具有多种颜色

regex - 从文本中捕获两位数字