Powershell在ISE中正确错误,但在命令行执行中没有

问题描述 投票:1回答:3

我正在PowerShell ISE中运行一个命令,它正在退出我的预期,但当我将代码移动到命令行以在不同的环境中执行时,我不再接收错误了。该错误仅发生在ISE中。我试图在命令行上使用-sta像其他人一样,但没有运气。

$SIEBEL_HOME\srvrmgr.exe /c "Run Command"
echo "Exit Code: $lastExitCode - Return Code: $?"

当我通过ISE运行时,我得到以下输出:

Exit Code: 0 - Return Code: False

当我在命令行上运行该命令时,我得到以下输出:

E:\powershell.exe -sta -file script.ps1

Exit Code: 0 - Return Code: True

正如您所看到的,我正在尝试检查返回代码并在ISE中获取正确的操作,但是没有通过命令行获得正确的结果。

我想知道在ISE中运行时Windows是否有不同的环境变量。我注意到当我通过ISE运行它时,控制台会以红色显示错误。

powershell powershell-v2.0 powershell-ise
3个回答
2
投票

$?变量仅检查最后执行的PowerShell命令的成功状态,而不是外部可执行文件。

$LASTEXITCODE变量检测外部可执行文件的最后退出代码。

如您所见,这些变量用于不同的目的,因此您不会看到它们之间的一致性。有关它们的更多信息,请运行以下命令:

 Get-Help -Name about_Automatic_Variables

编辑:运行此代码以显示$?变量工作。

# Here we'll show a successful command, and then a failed .NET method call
Write-Output -Object "hi"; # Run a successful command
Write-Host -Object $?; # True = command succeeded
[System.IO.File]::NonExistentMethod();
Write-Host -Object $?; # False = command failed

# Here we'll show a successful command, followed by a failed executable call
Write-Output -Object "hi" | Out-Null; # Run a successful command
Write-Host -Object $?; # True = last command ran successfully
ipconfig /nonexistentparameter | Out-Null;
Write-Host -Object $?; # False = last command did not run successfully

对我来说,运行PowerShell v3 Release Candidate,它在控制台中的工作方式与ISE相同。


1
投票

我有另一种解决方案。如果要编写一些代码来确定外部可执行文件的退出代码,可以使用Start-Process cmdlet。实际上,我通常建议人们使用Start-Process cmdlet而不是直接调用外部可执行文件,因为它有助于更​​好地处理参数值。在您的情况下,另一个好处是您可以使用-PassThru来表示-WaitStart-Process,这意味着您可以获得一个表示该过程的对象,该对象还将包含其退出代码。

$CliArgs = '/all';
$Process = Start-Process -FilePath ipconfig.exe -ArgumentList $CliArgs -NoNewWindow;
Write-Host -Object $Process.ExitCode;

0
投票

PowerShell ISE处理错误的方式与PowerShell控制台不同。在ISE中,从控制台应用程序到其stderr流的所有输出都将写入PowerShell的错误流。我还没有发现改变这种行为。

© www.soinside.com 2019 - 2024. All rights reserved.