[英]Suppress external command error output from Powershell $error
在我的个人资料中,我通过prompt
功能自定义了提示,以嵌入git分支信息:
function prompt
{
$prefix = ""
if ((test-path ".git") -or (test-path ".gitdir") -or ((git rev-parse --is-inside-work-tree 2> $null) -eq "true")) {
$prefix = "[git:" + (& git symbolic-ref --short HEAD) + "]"
}
write-host "PS $prefix $(get-location) >" -nonewline -foregroundcolor DarkMagenta
return " "
}
但是问题是,当我不在git树中时,即使我将错误重定向到$ null,检查的git rev-parse
部分也会在$error
插入错误。
这意味着$ error会因以下错误而受到污染,因为每次提示呈现时都会生成该错误:
git : fatal: Not a git repository (or any of the parent directories): .git
At C:\temp\prompt.ps1:4 char:64
+ ... ".gitdir") -or ((git rev-parse --is-inside-work-tree 2> $null) -eq "t ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
交互式运行时,我注意到2> $null
确实抑制了控制台的错误,但是该错误仍显示在$ error中:
PS C:\temp> $error
PS C:\temp> git rev-parse --is-inside-work-tree 2> $null
PS C:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:1
+ git rev-parse --is-inside-work-tree 2> $null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PS C:\temp>
我试过将命令包装在try {...} catch {}
,还使用了带有ignore的erroraction的invoke-command
,但都没有运气:
PS c:\temp> $error.clear()
PS c:\temp> $error
PS c:\temp> invoke-command -scriptblock { git rev-parse --is-inside-work-tree 2> $null } -erroraction ignore
PS c:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:31
+ ... d -scriptblock { git rev-parse --is-inside-work-tree 2> $null } -erro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PS c:\temp> $error.clear()
PS c:\temp> $error
PS c:\temp> try { git rev-parse --is-inside-work-tree 2> $null } catch { }
PS c:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:7
+ try { git rev-parse --is-inside-work-tree 2> $null } catch { }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PS c:\temp>
如何抑制此错误添加到$error
,使其保持干净?
不幸的是,从PowerShell Core 6.2.1 / Windows PowerShell v5.1开始,使用2>$null
抑制来自外部程序的stderr输出意外地仍然通过Powershell的错误流(流2
)绕行,因此输出仍记录在$Error
。 GitHub问题中描述了此已知问题。
作为一种解决方法,您可以通过cmd /c
(或在Unix上为sh -c
)调用git
,并使其进行重定向:
# Windows
cmd /c 'git rev-parse --is-inside-work-tree 2>NUL'
# Linux, macOS
sh -c 'git rev-parse --is-inside-work-tree 2>/dev/null'
如您所述,这将正确传递git
的退出代码,因此您之后可以通过$LASTEXITCODE
确定成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.