PowerShell 5.1中2>$null重定向是否仍可正常工作?
PowerShell错误重定向失效的原因及解决办法
问题现象
你尝试用2>$null或Out-Null忽略PowerShell中的错误,但以下场景均无效:
- 调用不存在的cmdlet,即使加
2>$null仍显示错误:
PS C:\WINDOWS\system32> asdf 2>$null asdf : The term 'asdf' is not recognized as the name of a cmdlet...
- 调用.NET方法(如
Substring)抛出异常时,2>$NULL和| out-null都无法屏蔽错误:
PS C:\WINDOWS\system32> $qwerty = "a" PS C:\WINDOWS\system32> $qwerty.substring(0,2) 2>$NULL Exception calling "Substring" with "2" argument(s): "Index and length... PS C:\WINDOWS\system32> $qwerty.substring(0,2) | out-null Exception calling "Substring" with "2" argument(s): "Index and length...
核心原因
PowerShell的错误分为两类,2>$null仅能处理非终止错误(cmdlet返回的非严重错误,不会中断执行),而你遇到的是终止错误(即异常):
- 调用不存在的cmdlet属于「命令未找到终止错误」,这类错误会直接中断流程,不通过标准错误流(stderr)输出,所以
2>$null捕获不到。 - .NET方法抛出的是**.NET异常**,属于终止错误,同样不走stderr,
Out-Null仅能丢弃标准输出,对错误无作用。
解决办法
1. 用try/catch捕获异常
适合需要针对性处理异常的场景,直接忽略的话可以留空catch块:
# 处理Substring异常 try { $qwerty = "a" $qwerty.Substring(0, 2) } catch { # 无操作即忽略异常 } # 处理不存在的cmdlet try { asdf } catch { # 忽略异常 }
2. 临时修改错误偏好或用-ErrorAction参数
- 对cmdlet直接使用
-ErrorAction SilentlyContinue参数:
asdf -ErrorAction SilentlyContinue
- 对.NET方法,临时修改全局错误偏好(用完建议恢复原值):
$originalErrorPref = $ErrorActionPreference $ErrorActionPreference = 'SilentlyContinue' $qwerty = "a" $qwerty.Substring(0, 2) $ErrorActionPreference = $originalErrorPref
3. 全局设置错误偏好(不推荐)
如果需要全局忽略所有终止错误,可以修改$ErrorActionPreference,但容易隐藏其他潜在问题,谨慎使用:
$ErrorActionPreference = 'SilentlyContinue' asdf $qwerty = "a" $qwerty.Substring(0, 2) # 恢复默认设置 $ErrorActionPreference = 'Continue'
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

