powershell - Powershell错误在ISE中正确输出,但在命令行执行中不正确

标签 powershell powershell-2.0 powershell-ise

我正在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中获得正确的操作,但是没有通过命令行获得正确的结果。

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

最佳答案

$?变量仅检查上一次执行的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相同。

关于powershell - Powershell错误在ISE中正确输出,但在命令行执行中不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11402473/

相关文章:

powershell - 如何从DateTime对象获取日历的开始时间?

c# - .net 中的 Powershell 版本兼容性

mysql - PowerShell MySQL 查询语法

powershell - 告诉PowerShell ISE不要将stderr发送给Write-Error

powershell - 通过带有返回码的 VBS 隐藏 PS 窗口

powershell - 有没有办法在 Powershell 脚本中访问 TeamCity 系统属性?

c# - 如何将 C# 代码转换为 PowerShell 脚本?

powershell - 在 powershell WebClient 和 FileStream 中使用相对路径

powershell - 外主机 - 寻呼错误 "The method or operation is not implemented. "(ISE)

PowerShell ISE 如何使用 ScriptBlock 关闭自动创建新选项卡?