繁体   English   中英

抑制和处理 PowerShell 脚本中的 stderr 错误输出

[英]Suppress and handle stderr error output in PowerShell script

我想使用 PowerShell 捕获 SMB 共享,但这不起作用

# Cannot use CIM as it throws up WinRM errors.
# Could maybe use if WinRM is configured on all clients, but this is not a given.
$cim = New-CimSession -ComputerName $hostname
$sharescim = Get-SmbShare -CimSession $cim

所以这导致我使用网络视图的另一种方法,如果主机是 Windows,这是相当好的

# This method uses net view to collect the share names (including hidden shares like C$) into an array
# https://www.itprotoday.com/powershell/view-all-shares-remote-machine-powershell
try { $netview = $(net view \\$hostname /all) | select -Skip 7 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk*'|out-null ; $matches[1]} }
catch { $netview = "No shares found" }

所以,如果主机是 Linux,我会收到一个错误,如您所见,我在上面尝试使用 try / catch 来抑制该错误,但这失败了。

显然,这是因为“网络视图”是 CMD,因此无法通过 try / catch 控制。 所以我的问题是:我怎样才能a)抑制下面的系统错误?b)当它发生时处理这个错误(即抛出“这个主机没有响应'net view'”或其他东西而不是错误)?

System error 53 has occurred.
The network path was not found.

来自外部程序的 Stderr(标准错误)输出未与 PowerShell 的错误处理集成,主要是因为此流不仅用于传达错误,还用于传达状态信息。
(因此,您应该只从其退出代码推断外部程序调用的成功与失败,如$LASTEXTICODE [1]中所反映的)。

但是,您可以重定向stderr 输出,并将其重定向到$null ( 2>$null ) 使其静音[2]

$netview = net view \\$hostname /all 2>$null | ...
if (-not $netview) { $netview = 'No shares found' }

[1] 对非零退出代码执行操作,按照惯例表示失败,从 v7.1 开始,它也没有集成到 PowerShell 的错误处理中,但是在这个 RFC中提出了修复这个问题。

[2] 在 PowerShell 7.1.x 之前,任何2>重定向都会意外在自动$Error集合中记录 stderr 行。 此问题已在 v7.1 中得到纠正
作为一个不幸的副作用,在 v7.0 之前的版本中,如果$ErrorActionPreference = 'Stop'恰好生效,并且至少发出一条 stderr 行,则2>重定向也可能引发脚本终止错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM