简体   繁体   中英

Suppress and handle stderr error output in PowerShell script

I wanted to capture SMB shares using PowerShell, but this doesn't work

# 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

So this led me to another method using net view and this is fairly ok if the host is 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" }

So, if the host is Linux, I get an error, and as you can see, I am trying above to suppress that error with try / catch, but this fails.

Obviously, this is because 'net view' is CMD so is not controllable by try / catch. So my question is: how can I a) suppress the system error below?, and b) handle this error when it happens (ie throw a "This host is not responding to 'net view'" or something instead of the error)?

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

Stderr (standard error) output from external programs is not integrated with PowerShell's error handling , primarily because this stream is not only used to communicate errors , but also status information.
(You should therefore only infer success vs. failure of an external-program call from its exit code , as reflected in $LASTEXTICODE [1] ).

However, you can redirect stderr output, and redirecting it to $null ( 2>$null ) silences it [2] :

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

[1] Acting on a nonzero exit code, which by convention signals failure, is also not integrated into PowerShell's error handling as of v7.1, but fixing that is being proposed in this RFC .

[2] Up to PowerShell 7.1.x, any 2> redirection unexpectedly also records the stderr lines in the automatic $Error collection. This problem has been corrected in v7.1
As an unfortunate side effect, in versions up to v7.0, a 2> redirection can also throw a script-terminating error if $ErrorActionPreference = 'Stop' happens to be in effect, if at least one stderr line is emitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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