如何使用Powershell获取打印服务器上的打印机共享?

我试图使用Powershell从远程打印服务器获取打印份额。

我在用着:

Get-WmiObject Win32_Share -computerName "print-server" 

我得到一个“访问被拒绝”的错误:

 Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) At line:1 char:14 + Get-WmiObject <<<< Win32_Share -computerName "print-server" + CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand 

但是,我不明白为什么我可以看到这些共享,就好像我通过“我的电脑”连接(例如\\ print-server \),我可以看到所有的打印份额。

有任何想法吗?

谢谢。

是的,你可以在Windows资源pipe理器中看到它们,但是由于你试图在远程机器上执行一个WMI查询,而你需要有效的凭据,所以你的Powershell命令会拒绝访问。

如果你想存储凭据,以便你可以非交互式地运行这个命令,你可以转换密码并将其作为一个安全string存储在一个文件中,但这只是模糊处理,任何智能的窥探都可以对其进行解码。

 Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File secret.txt $pass = Get-Content secret.txt | ConvertTo-Securestring $creds = New-Object -Typename System.Management.Automation.PSCredential -Argumentlist "domain\admin",$pass 

也许尝试放弃WMI查询路线。 也许尝试一个好的COM对象像这样:

 $network = New-Object -Com WScript.Network $network.AddWindowsPrinterConnection($printerShare) 

尝试使用Get-WmiObject传递凭据,如下所示。

$Credential = Get-Credential

(你会得到一个提示凭据)

Get-WmiObject Win32_Share -ComputerName 'PRINT-SERVER' -Credential $Credential