gpt4 book ai didi

powershell - 如何从 Switch 语句中退出 While 循环

转载 作者:行者123 更新时间:2023-12-03 00:42:30 27 4
gpt4 key购买 nike

在 PowerShell 中,如何退出嵌套在 switch 语句中的 while 循环,而不是立即执行 while 之后的代码堵塞?我似乎无法弄清楚。到目前为止,我尝试过的所有操作都会导致执行该代码块。

这是我想要完成的:

  1. 检查文件是否存在并通知用户文件是否存在检测到。
  2. 每 10 秒检查一次并通知用户
  3. 如果没有检测到文件,则退出循环切换,继续第 2 步
  4. 如果 30 秒后仍然检测到文件,则超时并退出整个脚本。

代码如下:

try {
#Step 1
$Prompt = <Some Notification Dialog with two buttons>
switch ($Prompt){
'YES' {
# Display the Windows Control Panel

#Wait for user to manually uninstall an application - which removes a file from the path we will check later.
$Timeout = New-Timespan -Seconds 30
$Stopwatch = [Dispatch.Stopwatch]::StartNew()

while ($Stopwatch.elapsed -lt $Timeout) {
if (Test-Path -Path "C:\SomeFile.exe" -PathType Leaf) {
Write-Host "The file is still there, remove it!"
return
}
Start-Sleep 10
}

#After timeout is reached, notify user and exit the script
Write-Host "Timeout reached, exiting script"
Exit-Script -ExitCode $mainExitCode #Variable is declared earlier in the script
}
'NO' {
# Do something and exit script
}
}

# Step 2
# Code that does something here

# Step 3
# Code that does something here
} catch {
# Error Handling Code Here
}

最佳答案

您可以使用带标签的 break 来退出特定循环(switch 语句算作一个循环),请参阅 about_break .

$a = 0
$test = 1
:test switch ($test) {
1 {
Write-Output 'Start'
while ($a -lt 100)
{
Write-Output $a
$a++
if ($a -eq 5) {
break test
}
}
Write-Output 'End'
}
}
Write-Output "EoS"

关于powershell - 如何从 Switch 语句中退出 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57556578/

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