Tell PowerShell ISE to not send stderr to Write-Error

大城市里の小女人 提交于 2019-12-04 03:05:41
hg st -R C:\Windows 2>&1 | %{ if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { $_ } }

This preserves the stderr output and sends it as normal output, rather than dropping it.

Redirecting the stderr output to stdout "should" work but it doesn't in ISE. In this case, your best bet is to silence the error output like so:

& {
    $ErrorActionPreference = 'SilentlyContinue'
    hg st -R C:\Windows 2>&1
}

By executing setting this variable in a nested scope, you avoid setting it globally. When the scope above is exited, the global version of $ErrorActionPreference is still set to whatever it was before.

It is unfortunate that ISE and the console behave differently but it is my understanding that with the "console", another console app just gets the console handle so it is outputting directly to the console (bypassing PowerShell). ISE isn't console based so it is trying to make native stderr play nicely with the PowerShell error stream. IMO the behavior of console isn't ideal in this case. So is it better to have ISE be consistent with console or better to have ISE handle stderr better (except the bit about not honoring stream redirection)? Obviously the PowerShell went with the latter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!