我正在尝试使用 Powershell 脚本创建网络打印机。下面的脚本可以毫无问题地创建端口,但不会创建队列。有人能确认这个脚本是否适用于 Windows Server 2008 吗?(注意,您需要安装驱动程序才能使其正常工作)。
function CreatePrinterPort {
Param (
[string]$IPAddress
)
$port = [wmiclass]"Win32_TcpIpPrinterPort"
$newPort = $port.CreateInstance()
$newport.Name= "IP_$IPAddress"
$newport.SNMPEnabled=$false
$newport.Protocol=1
$newport.HostAddress= $IPAddress
Write-Host "Creating Port $ipaddress" -foregroundcolor "green"
$newport.Put()
}
function CreatePrinter {
Param (
[string]$PrinterName,
[string]$DriverName,
[string]$IPAddress,
[string]$Location,
[string]$Comment
)
$print = [WMICLASS]"Win32_Printer"
$newprinter = $print.createInstance()
$newprinter.Drivername = $DriverName
$newprinter.PortName = "IP_$IPAddress"
$newprinter.Shared = $true
$newprinter.Sharename = $PrinterName
$newprinter.Location = $Location
$newprinter.Comment = $Comment
$newprinter.DeviceID = $PrinterName
Write-Host "Creating Printer $printername" -foregroundcolor "green"
$newprinter.Put()
}
CreatePrinterPort -IPAddress "Localhost"
CreatePrinter -PrinterName Print1 -DriverName "HP LaserJet 4" -PortName "Localhost"`
-Location "Office" -Comment "Test comment"
我收到的错误是在 CreatePrinter 函数上:
使用“0”个参数调用“Put”时发生异常:“一般失败”
答案1
您的 PortName 不应该是“IP_$IPAddress”而不是“Localhost”吗?
CreatePrinter -PrinterName Print1 -DriverName "HP LaserJet 4" -PortName "IP_123.123.123.123" -Location "Office" -Comment "Test comment"
此外,您的 DriverName 必须是该驱动程序的准确名称。您无法选择它;它由制造商指定。
答案2
您的脚本的问题在于您在函数中声明了 $IPAddress,但在调用该函数时指定了 -portname。请将函数更改为使用 $PortName,或在调用该函数时使用 -IPAddress。
我个人将您的功能更改为使用 [string]$PortName
这是您的功能正常运行
function CreatePrinter {
Param (
[string]$PrinterName,
[string]$DriverName,
[string]$PortName,
[string]$Location,
[string]$Comment
)
$print = [WMICLASS]"Win32_Printer"
$newprinter = $print.createInstance()
$newprinter.Drivername = $DriverName
$newprinter.PortName = "IP_$PortName"
$newprinter.Shared = $true
$newprinter.Sharename = $PrinterName
$newprinter.Location = $Location
$newprinter.Comment = $Comment
$newprinter.DeviceID = $PrinterName
Write-Host "Creating Printer $printername" -foregroundcolor "green"
$newprinter.Put()
}
$printerport1 = "10.10.10.0"
CreatePrinterPort -IPAddress $printerport1
CreatePrinter -PrinterName "Print1" -DriverName "HP LaserJet 4300 PCL 6" -PortName $printerport1 -Location "Office" -Comment "Test comment"