我在Powershell ISE(手动加载脚本并按F5)和Powershell控制台(执行脚本文件)中运行完全相同的script.ps1文件。 它们都有效,但ISE显示控制台没有的错误。为什么?
代码是:
git push origin master
Write-Host "lastExitCode: $lastExitCode Last command was successful: $?"
此代码在ISE中输出此错误:
git.cmd : Initializing to normal mode
At E:\script.ps1:28 char:4
+ git <<<< push origin master
+ CategoryInfo : NotSpecified: (Initializing to normal mode:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Initializing to normal mode
Everything up-to-date
lastExitCode: 0 Last command was successful: False
这在控制台中:
Everything up-to-date
lastExitCode: 0 Last command was successful: True
您可以看到成功状态也不一样。
我不知道他们为什么输出不同,但我们看到的信息 git push
斯特德尔正在过来。这意味着他们是 都 显示错误,虽然ISE使它们声音更大,并将其转换为错误 对象。
从PowerShell提示符考虑此输出:
PS> git push
Everything up-to-date
PS> git push 2> $null # Redirect stderr to $null
PS> $LastExitCode
1
PS>
并将其与ISE进行比较:
PS> git push
git : Everything up-to-date
At line:1 char:1
+ git push
+ ~~~~~~~~
+ CategoryInfo : NotSpecified: (Everything up-to-date:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PS> git push 2> $null
PS> $LastExitCode
1
PS>
除了显示错误对象的额外输出外,输出相同。 ISE已将stderr字符串转换为NativeCommandError对象,如果您看过红色,它甚至会显示错误消息。
我不知道他们为什么输出不同,但我们看到的信息 git push
斯特德尔正在过来。这意味着他们是 都 显示错误,虽然ISE使它们声音更大,并将其转换为错误 对象。
从PowerShell提示符考虑此输出:
PS> git push
Everything up-to-date
PS> git push 2> $null # Redirect stderr to $null
PS> $LastExitCode
1
PS>
并将其与ISE进行比较:
PS> git push
git : Everything up-to-date
At line:1 char:1
+ git push
+ ~~~~~~~~
+ CategoryInfo : NotSpecified: (Everything up-to-date:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PS> git push 2> $null
PS> $LastExitCode
1
PS>
除了显示错误对象的额外输出外,输出相同。 ISE已将stderr字符串转换为NativeCommandError对象,如果您看过红色,它甚至会显示错误消息。
如图所示 这个Stackoverflow的答案 阻止 git push
要打印到STDERR,解决方案就是调用命令 --porcelain
选项。
然后,打电话
git push origin master --porcelain
输出全部转到STDOUT
嗯,我能想到的唯一主要区别是ISE在v2中使用单线程单元(STA)模式,而控制台使用多线程单元(MTA)。您是否尝试使用-STA参数运行powershell.exe,或者使用-MTA运行powershell_ise.exe,然后再次尝试脚本?
看起来错误来自你试图运行的Git命令,FWIW。
所以,下面的例子有任何错误,这个命令-q 2>&1 | %{“$ _”}`将使错误结果无效。
解决方案和用途: git push -q 2>&1 | %{ "$_" }