簡體   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