关闭回声输出Powershell



我有一个获取共享大小的命令,但由于权限取决于谁自然运行脚本,它会向控制台发送错误。

 $shareSize = [math]::round((Get-ChildItem $($share.path) -Recurse -Force | Measure-Object -Property Length -Sum ).Sum/1GB)

我想抑制错误,比如如果可能的话关闭ECHO?

您可以通过将错误流重定向到$null来抑制错误消息,例如:

[math]::round((Get-ChildItem $($share.path) -Recurse -Force 2>$null

您可以将ErrorAction参数添加到对Get-ChildItem的调用中(我认为这是错误的来源),如下所示:

 $shareSize = [math]::round((Get-ChildItem $($share.path) -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum ).Sum/1GB)

有关更多详细信息,请查看ErrorAction和$ErrorActionPreference内置变量(获取有关_Preference_Variables的帮助)。注意这些选项——隐藏错误通常不是一个好主意。

最新更新