I have a little function to get all printer objects from a print server, the cmdlet throws an error if the spooler service is not available (e.g. the hostname is wrong). I want to catch that error message with a try catch, but it wont catch? Can someone explain this behavior to me?
Code:
Function GetAllPrinters
{
param
(
[Parameter(Mandatory=$true)]
[string]$PrintServerHostName
)
try {
$Printers = Get-Printer -ComputerName $PrintServerHostName
}
catch {
Write-Host "Could not receive information from the print server $PrintServerHostName."
exit 1001
}
return $Printers
}
Error Message:
Get-Printer : Der Spoolerdienst ist nicht erreichbar. Stellen Sie sicher, dass der Spoolerdienst ausgeführt wird.
In C:\Users\f.zedler\Desktop\GetPrintServerStatus.ps1:34 Zeichen:21
+ $Printers = Get-Printer -ComputerName $PrintServerHostName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (MSFT_Printer:ROOT/StandardCimv2/MSFT_Printer) [Get-Printer], CimException
+ FullyQualifiedErrorId : HRESULT 0x800706ba,Get-Printer
You're running into the concept of a Terminating versus a non-terminating error.
Some functions can throw an error but still continue without any issues, they might just throw an error to the error stream and keep on trucking. We'd call these a non-terminating error.
Others could leave you in a bad situation or cause issues, and it'd be better for them to error and stop. We call these terminating errors.
Terminating error have the nice value-add in that they are capable of triggering a try/catch
block, while most other errors will not.
This function seems to be throwing a non-terminating error, which ignores try/catch
blocks. You can override this though, by specifying a choice for -ErrorAction
, which is a common parameter, one that's available for all cmdlets.
Your choices are this:
So, in conclusion, since it looks like your function is ignoring your try/catch
block, try and add -ErrorAction STOP
. That will probably solve this problem.
Get-Printer -ErrorAction Stop
Try it with Get-Printer -ComputerName $PrintServerHostName -ErrorAction Stop
or set $erroractionpreference
to stop.
FYI on my script below, I had to move the "-erroraction stop" option before the first pipe symbol.
$e=Get-Printer -ComputerName $lbpclist.SelectedItem -ErrorAction stop | Where-Object {$_.Name -like $txtPrinterName.Text
User contributions licensed under CC BY-SA 3.0