【发布时间】:2021-01-19 14:18:30
【问题描述】:
我想使用 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) handle 这个错误发生时(即抛出“此主机没有响应'net view'”或东西而不是错误)?
System error 53 has occurred.
The network path was not found.
【问题讨论】:
-
顺便说一句:您不需要
$(...)来运行外部程序;简而言之:$(...)仅在可扩展字符串 ("...") 中或在其他语句中嵌入整个语句时需要。 -
另一边:
net.exe是一个控制台应用程序,因此与任何特定的 shell 无关。作为一个控制台应用程序,它只有两个输出流可供使用:stdout(标准输出),用于数据,stderr(标准错误)用于错误消息和/或状态消息。
标签: powershell networking ip stderr smb