gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:22:45 24 4
gpt4 key购买 nike

我想从脚本中的一个部分跳转到同一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com