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

Kis*_*asi 3 powershell scripting

在 PowerShell 中,如何退出嵌套在语句while内的循环switch,而不执行紧随该块之后的代码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
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以使用带有标签的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"
Run Code Online (Sandbox Code Playgroud)