PowerShell exit() 杀死 shell 和 ISE

Gar*_*arr 2 powershell exit powershell-ise

所以我写了一系列的函数并将它们插入到一个 PS 模块 (.psm1) 中。其中之一是一个简单的 ErrorAndExit 函数,它将消息写入 STDERR,然后调用exit(1);,这是一种允许轻松重定向错误消息的习惯。在调试我的脚本时,在普通的 PowerShell 或 ISE 中,如果我调用一个函数,该函数又调用 ErrorAndExit,它不仅会退出脚本,还会退出整个 PowerShell 进程。终端和 ISE 都会立即死亡。终端,我可能只是理解,但是ISE?!最令人沮丧的部分当然是在窗口消失之前我看不到错误消息。

我相信这与我的调试方式有关 - 我已经定义了很多发生在链中的函数,并且已经注释掉了启动链的调用。我正在导入脚本并从提示中调用函数。由于脚本是为自动化设计的,在实际使用中杀掉整个PS进程不会有问题,但我需要看看调试输出是什么。

有问题的函数,在 Common.psm1 中:

function errorAndExit([string]$message)
{
    logError($message);
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)

logError通过$messageWrite-Error。此调用导致 PS 或 ISE 终止的示例函数:

function branch([string]$branchName, [int]$revision, [string]$jenkinsURL, [switch]$incrementTrunk)
{
    Set-Variable -Name ErrorActionPreference -Value Stop;
    log("Script starting, parameters branchName=$branchName, revision=$revision, jenkinsURL=$jenkinsURL");
    if (-not ($branchName -match "\d{4}\.\d{2}\.\d"))
    {
        errorAndExit("Provided branch name $branchName is not a valid YYYY.MM.R string");
    }
...
Run Code Online (Sandbox Code Playgroud)

我的 Common.psm1 模块正在使用一个简单的Import-Module -Force "$PSScriptRoot\Common";. 从 PS 提示符调用时:

PS C:\Windows\system32> branch -branchName abc
Run Code Online (Sandbox Code Playgroud)

导致 PowerShell 或 ISE 完全退出。

我是从 Bash 心态来到 PowerShell 的,并且已经编写了这样的脚本(但是已经习惯了传递对象),但这不是我期望从任何脚本语言中获得的行为。

Chr*_*wis 6

在 Powershell ISE 中,该exit命令会关闭整个 IDE,而不仅仅是当前的命令选项卡。

https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/13223112-would-be-better-if-the-exit-command-in-powershell

exit的 errorAndExit 函数的使用有一点缺陷。如前所述,athrow或 areturn $false并评估结果将是更好的选择。