我无法运行调用命令脚本在远程机器上安装打印机。我的代码在本地运行,但一旦我将其通过管道传输到 Invoke-command 中,我就会收到错误。
本地:
$Printer = "\\server1\printer1"
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($Printer)
这就很好地添加了打印机。我可以毫无问题地在远程计算机上执行相同的命令。但是当我尝试远程执行命令时,我遇到了问题。
远程:
$compname = "computer"
$Printer = "\\server1\printer1"
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')}
返回错误“打印机名称无效”
所以我尝试使用以下代码查看 shell 发送到远程计算机的内容,写入输出中的所有内容看起来都不错,但我仍然遇到错误:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer'); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')"}
输出:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : computer
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('\\server1\printer1')
编辑 1/5/2015
所以我尝试了 Paul 的代码,其中包含许多不同的参数列表条目。到目前为止,一切都没有奏效。我认为前 3 个更接近答案。
-ArgumentList ""\\server1\printer1""
-ArgumentList ""'\\server1\printer1'""
-ArgumentList "\"\\server1\printer1""
结果:
Invoke-Command : A positional parameter cannot be found that accepts argument '\\server1\printer1'.
At line:1 char:1
+ Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Ne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
-ArgumentList "'\\server1\printer1'"
-ArgumentList \'"\\server1\printer1"'
-ArgumentList \""\\server1\printer1""
-ArgumentList \"\\server1\printer1"
结果:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : sso-mxl327082y
最佳答案
试试这个:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($args[0]); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($($args[0]))"} -ArgumentList "\\server1\printer1"
我认为这是因为您的 $printer
变量放在单引号之间,单引号之间的变量不会被 powershell 解释。所以你的函数可能得到的打印机名称是“$printer”。
如果您想知道它在您的 write-host
语句中是否正确打印出来,因为这里的单引号在字符串中。
关于powershell - 通过 Powershell 将共享打印机添加到远程计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746731/