PowerShell exit() 杀死 shell 和 ISE

PowerShell exit() kills shell and ISE

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

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

Common.psm1 中的相关函数:

function errorAndExit([string]$message)
{
    logError($message);
    exit(1);
}

其中 logError$message 传递给 Write-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");
    }
...

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

PS C:\Windows\system32> branch -branchName abc

导致 PowerShell 或 ISE 完全退出。

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

我不确定您为什么不能 throw 您的错误消息。如果您必须使用 exit 中的 return 代码,但又不想在 ISE 中这样做,请考虑更改您的函数:

function errorAndExit([string]$message)
{
    logError $message
    if ($Host.Name -eq 'Windows PowerShell ISE Host') {
        throw $message
    } else {
        exit 1
    }
}

尝试 Throw 关键字,它用于引发异常,您稍后可以在 try-catch 块中使用。

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

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

您对 exit 的使用在您的 errorAndExit 函数中存在一点缺陷。如前所述,throwreturn $false 并评估结果是更好的选择。