Powershell Switch Break Label 未执行

Itc*_*don 3 powershell break

作为更大脚本的一部分,我已经实现了switch下面的详细内容。目的是当脚本执行时,用户可以选择

  1. 在屏幕上输入要迁移的用户,或
  2. 从文件导入。

如果选择了从文件导入选项 - 我想测试文件是否存在 - 如果没有,我想突破并返回到开关标签:choose。但是,当我选择从文件导入选项并提供不存在的路径时,脚本会继续运行并且不会中断或返回标签。我哪里错了?

$chooseInputMethod = @"
This script migrates one or more user accounts between two trusted domains in a forest e.g. from domain1 to domain2 (or vice versa)

Select method to specify user(s) to migrate:

1. Enter name(s) on-screen (default)
2. Import name(s) from file

Enter selection number
"@

$choosePath = @"
Enter path to file..

Notes

  - Filename: 
    If file is located in script directory ($pwd) you can enter the filename without a path e.g. users.txt

  - No quotation marks: 
    DO NOT put any quotes around the path even if it contains spaces e.g. e:\temp\new folder\users.txt

Enter path or filename
"@

$enterUsernames = @"
Enter username(s) seperate each with a comma e.g. test1 or test1,test2,test3`n`nEnter name(s)
"@

cls
:choose switch (Read-Host $chooseInputMethod) {
    1 { cls; $usersFromScreen = Read-Host $enterUsernames }
    2 {
        cls;
        $usersFromFile = Read-Host $choosePath;
        if (-not (Test-Path $usersFromFile -PathType Leaf)) {
            break choose
        }
    }
    default { cls; $usersFromScreen = Read-Host $enterUsernames }
}

Write-Host "hello"
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 5

文档中break

在 PowerShell 中,只有循环关键字,例如 Foreach、For 和 While 可以有标签。

因此,switch即使它具有循环功能,在这种情况下也不被视为循环。

但是,在这种情况下,我不明白为什么break没有标签是不够的。

  • Switch 可以有标签,并且可以循环。 (2认同)