Reputation: 23
<# Declare name of the Port #>
$portName = "TCPPort:xx.xx.xx.xx"
<# Declares the name of the Printers Driver #>
$printDriverName = "HP LaserJet Pro M402-M403 PCL 6"
<# If the printer exists, get the port for it, and assign the name of it to -Name $portname #>
$portExists = Get-Printerport -Name $portname -ErrorAction SilentlyContinue
<# If the Port does not exist, Add the provided port name, assign it as the Printerhostaddress #>
if (-not $portExists) {
Add-PrinterPort -name $portName -PrinterHostAddress ""
}
$printDriverExists = Get-PrinterDriver -name $printDriverName -ErrorAction SilentlyContinue
<# Once the PrintDriver is obtained, Add the Printer, assign the name,portname, and driver name. Install to designated system #>
if ($printDriverExists){
Add-Printer -Name "CRCHRDirHP2" -PortName $portName -DriverName $printDriverName
}else{
Write-Warning "Printer Driver not installed"
}
Upvotes: 2
Views: 2474
Reputation: 1283
In addition to Santiago's answer, if you have some source for the variables it would make things a lot easier. For instance consider the following CSV file 'printers.csv' in C:\Temp:
name,portName,driverName
CRCHRDirHP2,TCPPort123,HP LaserJet
CRCHRDirHP3,TCPPort1234,HP LaserJet
CRCHRDirHP4,TCPPort12345,HP LaserJet
Now we import the file and start looping through the printers to call the function that Santiago made and use the variables from the input file.
$printers = Import-CSV C:\Temp\printers.csv
foreach($printer in $printers){
Write-Verbose "Processing printer $($printer.name)"
try{
Install-Printer -PrinterName $printer.name -PortName $printer.portName -DriverName $printer.driverName
}catch{
Write-Verbose "Printer $($printer.name) failed with error: $_"
}
}
Upvotes: 0
Reputation: 61083
This is an example of how your code would look if it was a function, I've changed the if
statements for try / catch
statements. The function is using [cmdletbinding()]
, this will allow you to use CommonParameters, in example, -Verbose
if you want to display the Write-Verbose
comments.
function Install-Printer {
[cmdletbinding()]
param(
[Parameter(Mandatory)]
[string]$PrinterName,
[Parameter(Mandatory)]
[string]$PortName,
[Parameter(Mandatory)]
[string]$DriverName
)
try
{
Write-Verbose 'Attempting to get Printer Port'
# If this fails, it will go to `catch` block
$null = Get-Printerport -Name $PortName
}
catch
{
Write-Verbose 'Port does not exist. Adding new Printer Port.'
Add-PrinterPort -Name $PortName -PrinterHostAddress ""
}
try
{
Write-Verbose 'Adding printer...'
$null = Get-PrinterDriver -Name $DriverName
Add-Printer -Name $PrinterName -PortName $PortName -DriverName $DriverName
Write-Verbose 'Printer added successfully.'
}
catch
{
Write-Verbose 'Failed to add printer, error was:'
$PSCmdlet.WriteError($_)
}
}
Install-Printer -PrinterName "CRCHRDirHP2" -PortName "TCPPo...." -DriverName "HP LaserJet..."
Upvotes: 2