Powershell Try Catch on Get-Printer


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?


Function GetAllPrinters
    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
asked on Stack Overflow Jan 17, 2017 by kami

3 Answers


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:

  • Inquire - ask you to continue or not
  • Continue - keep on trucking but write out error messages
  • SilentlyContinue - keep on trucking but sweep the error under the rug (silently!)
  • STOP - this is the one you want

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
answered on Stack Overflow Jan 17, 2017 by FoxDeploy

Try it with Get-Printer -ComputerName $PrintServerHostName -ErrorAction Stop or set $erroractionpreference to stop.

answered on Stack Overflow Jan 17, 2017 by 4c74356b41

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
answered on Stack Overflow Aug 24, 2020 by Jamal • edited Aug 24, 2020 by Dharman

User contributions licensed under CC BY-SA 3.0