PowerShell中while循环中switch语句的问题

拉米尔

无论出于何种原因,While 循环自己工作,Switch 语句自己工作,当我将它们组合起来时..While 循环工作正常,但 Switch 语句.. 不是那么多。

y 或 n 只是 While 循环接受的值,问题是当我给它 y 或 n 时,没有任何代码被执行,脚本刚刚完成。

PowerShell 版本为 5.1。

While (($UserInput = Read-Host -Prompt "Are you sure? (y/n)") -notmatch '^n$|^y$') {
    Switch ($UserInput) {
        'y' {
            Try {
                Write-Output "Success."
        }
            Catch {
                Write-Output "Error."
            }
        }
        'n' {
            Write-Output "Cancelled."
        }
    }
}
穆迪·巴赫迪亚

您正在使用-notmatch. 因此While循环导致错误并且循环没有被执行。由于您想执行脚本直到获得“y”或“n”作为输入,因此只需使用!which 将执行脚本,直到它接收到“y”或“n”作为输入。使用以下代码:

While (!($UserInput = Read-Host -Prompt "Are you sure? (y/n)") -notmatch '^n$|^y$') {
Switch ($UserInput) {
    'y' {
        Try {
            Write-Output "Success."
    }
        Catch {
            Write-Output "Error."
        }
    }
    'n' {
        Write-Output "Cancelled."
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章