我一直在寻找一种方法,在函数中发生不可恢复的错误时终止PowerShell (PS1)脚本。例如:
function foo() {
# Do stuff that causes an error
$host.Exit()
}
当然,没有$host.Exit()这样的东西。有$host.SetShouldExit(),但这实际上关闭了控制台窗口,这不是我想要的。我需要的是一些相当于Python的sys.exit(),它将简单地停止当前脚本的执行,而不需要进一步的告别。
编辑:是的,只是退出。咄。
我知道这是一个老帖子,但我发现自己经常回到这个帖子,因为它是搜索这个主题时的头号搜索结果之一。然而,我总是离开比我来的时候更困惑,因为相互矛盾的信息。最终,我总是不得不执行自己的测试来弄清楚。所以这次我将把我的发现发布出来。
大多数人都希望使用Exit来终止正在运行的脚本。然而,如果你的脚本只是声明了稍后在shell中使用的函数,那么你就需要在函数的定义中使用Return。
退出vs返回vs打破
Exit: This will "exit" the currently running context. If you call this command from a script it will exit the script. If you call this command from the shell it will exit the shell.
If a function calls the Exit command it will exit what ever context it is running in. So if that function is only called from within a running script it will exit that script. However, if your script merely declares the function so that it can be used from the current shell and you run that function from the shell, it will exit the shell because the shell is the context in which the function contianing the Exit command is running.
Note: By default if you right click on a script to run it in PowerShell, once the script is done running, PowerShell will close automatically. This has nothing to do with the Exit command or anything else in your script. It is just a default PowerShell behavior for scripts being ran using this specific method of running a script. The same is true for batch files and the Command Line window.
Return: This will return to the previous call point. If you call this command from a script (outside any functions) it will return to the shell. If you call this command from the shell it will return to the shell (which is the previous call point for a single command ran from the shell). If you call this command from a function it will return to where ever the function was called from.
Execution of any commands after the call point that it is returned to will continue from that point. If a script is called from the shell and it contains the Return command outside any functions then when it returns to the shell there are no more commands to run thus making a Return used in this way essentially the same as Exit.
Break: This will break out of loops and switch cases. If you call this command while not in a loop or switch case it will break out of the script. If you call Break inside a loop that is nested inside a loop it will only break out of the loop it was called in.
There is also an interesting feature of Break where you can prefix a loop with a label and then you can break out of that labeled loop even if the Break command is called within several nested groups within that labeled loop.
While ($true) {
# Code here will run
:myLabel While ($true) {
# Code here will run
While ($true) {
# Code here will run
While ($true) {
# Code here will run
Break myLabel
# Code here will not run
}
# Code here will not run
}
# Code here will not run
}
# Code here will run
}