Powershell v2 - 安装打印机



我正在尝试使用Powershell脚本在Windows 7 x64上自动安装打印机。到目前为止,我有一个脚本成功创建了TCP/IP端口,但给了我一个错误 - 当它执行代码的打印机安装部分时,参数无效。关于如何解决问题并通过Powershell成功安装打印机的任何想法?代码如下:

$hostAddress = "172.16.2.24" 
$portNumber = "9100"  
$computer = $env:COMPUTERNAME 
$wmi= [wmiclass]"\$computerrootcimv2:win32_tcpipPrinterPort" 
#$wmi.psbase.scope.options.enablePrivileges = $true 
$newPort = $wmi.createInstance() 
$newPort.hostAddress = $hostAddress 
$newPort.name = "IP_" + $hostAddress 
$newPort.portNumber = $portNumber 
$newPort.SNMPEnabled = $false 
$newPort.Protocol = 1 
$newPort.put()
CMD.EXE /C "printui.exe /if /b "Test Printer" /f C:inetpubwwwrootftpPrdriversHP Universal Print Driverpcl6-x64-5.7.0.16448hpbuio100l.inf /r "IP_172.16.2.24" /m "HP Laser Jet P3015""

问题更新:这是有效的CMD代码,那么如何将其合并到上面的Powershell代码中?

printui.exe /if /b "HP Universal Printing PCL 6" /f "C:inetpubwwwrootftpPrdriversHP Universal Print Driverpcl6-x64-5.7.0.16448hpbuio100l.inf" /u /r "IP_172.16.2.24" /m "HP Universal Printing PCL 6"

要在双引号字符串中嵌入双引号,您需要对它们进行转义。 由于您没有使用变量,因此使用单个带引号的字符串更容易,例如:

CMD.EXE /C 'printui.exe /if /b "Test Printer" /f C:inetpubwwwrootftpPrdriversHP Universal Print Driverpcl6-x64-5.7.0.16448hpbuio100l.inf /r "IP_172.16.2.24" /m "HP Laser Jet P3015"'

如果需要在此字符串中使用 PowerShell 变量,则需要切换回双引号并转义必要的 DQ 字符,例如:

CMD.EXE /C "printui.exe /if /b `"$PrinterName`" /f C:inetpubwwwrootftpPrdriversHP Universal Print Driverpcl6-x64-5.7.0.16448hpbuio100l.inf /r `"IP_172.16.2.24`" /m `"HP Laser Jet P3015`""

抱歉,但我不确定您为什么要将CMD/C称为@PARAMS。 我只是直接调用 printui.exe它正在工作,我只双引用 Args

# Printer Info, I keep this in an SQL DB, and return these values with a query:
$printerID = "<PrinterNameOrID>"
$printerIP = "<PrinterIP>"
$printerPort = "IP_$printerIP"
$printerModel = "<PrinterModelFromINF>"
$driverINFPath = "<UNCPathToDriverINF>"
# Build a new Local TCP Printer Port, naming it with values unique to the Printer ID:
$newPort = ([wmiclass]"Win32_TcpIpPrinterPort").CreateInstance()
$newPort.HostAddress = $printerIP
$newPort.Name = $printerPort
$newPort.PortNumber = "9100"
$newPort.Protocol = 1
$newPort.Put()
# Add the printer
printui.exe /if /b "$printerID" /f "$driverINFPath" /u /r "$printerPort" /m "$printerModel"
我知道

这已经得到了回答,但你可以借用我在这个Excel工作簿中的代码(文章中有一个链接)。 我意识到它使用 VBS,但这些是内置在 Windows 中的脚本中,剪切/粘贴到 Excel 中为我节省了很多次,我已经以这种方式安装了数千台打印机

打印机创建的最佳工具-Excel 与打印管理-控制台

试试这个:

runas /user:Contoso.comuser1 "printui.exe /if /b "Test Printer" /f "C:inetpubwwwrootftpPrdriversHP Universal Print Driverpcl6-x64-5.7.0.16448hpbuio100l.inf" /r "IP_172.16.2.24" /m "HP Laser Jet P3015""

最新更新