135

When my PowerShell script tries, for example, to create a SQL Server object for a server that doesn't exist ("bla" in my case), PowerShell displays lots of PowerShell errors in red.

Since my script checks the value of $? after such calls, and displays and logs errors, I'd rather not have the several lines of PowerShell errors displayed as well.

How can I deactivate those being displayed for my script?

9 Answers 9

195

You have a couple of options. The easiest involve using the ErrorAction settings.

-Erroraction is a universal parameter for all cmdlets. If there are special commands you want to ignore you can use -erroraction 'silentlycontinue' which will basically ignore all error messages generated by that command. You can also use the Ignore value (in PowerShell 3+):

Unlike SilentlyContinue, Ignore does not add the error message to the $Error automatic variable.

If you want to ignore all errors in a script, you can use the system variable $ErrorActionPreference and do the same thing: $ErrorActionPreference= 'silentlycontinue'

See about_CommonParameters for more info about -ErrorAction. See about_preference_variables for more info about $ErrorActionPreference.

3
  • 1
    do you need single quote in -erroraction 'silentlycontinue'? Intellisese is showing options and not adding single quote.
    – PAS
    Apr 24, 2019 at 16:55
  • 2
    If the format above doesn't work for you, reference the link provided above. I had to format as -ErrorAction:SilentlyContinue in PS 5.1. I was calling my cmdlet from batch so I don't know if that makes a difference. But good info when you know an acceptable error may be thrown.
    – David
    Dec 31, 2019 at 19:30
  • 2
    --rm .\Windows.old\ -Force -Recurse -Verbose -ErrorAction SilentlyContinue -WarningAction SilentlyContinue </code> Mar 1, 2020 at 1:07
26

You can also append 2>$null to your command.

Example:

$rec = Resolve-DnsName $fqdn -Server $dns 2>$null
3
  • 4
    Though it may not be the "proper" way, this is perfect for handling broken CmdLets that output errors no matter the error preference switch or variable. Just had to do this for Get-CsOnlineVoiceUser version 3.1.1, which must use Get-CsUser under the hood without properly handling its errors. Feb 21, 2022 at 20:49
  • This one works when executing non-powershell commands in powershell. For example, only this solution works when calling "taskkil" Nov 1, 2022 at 12:48
  • So how do I do this per selective line? I have this simple script that restores my quick access pins but sometimes I move folders and the commands for those specific entries just point to a null object, hence the errors... which is fine. I can't seem to make it work this way... only with try catch which is a bit more to write than 2>$null, pardon my laziness
    – JasonXA
    Feb 11 at 0:40
24

Windows PowerShell provides two mechanisms for reporting errors: one mechanism for terminating errors and another mechanism for non-terminating errors.

Internal CmdLets code can call a ThrowTerminatingError method when an error occurs that does not or should not allow the cmdlet to continue to process its input objects. The script writter can them use exception to catch these error.

EX :

try
{
  Your database code
}
catch
{
  Error reporting/logging
}

Internal CmdLets code can call a WriteError method to report non-terminating errors when the cmdlet can continue processing the input objects. The script writer can then use -ErrorAction option to hide the messages, or use the $ErrorActionPreference to setup the entire script behaviour.

8

I had a similar problem when trying to resolve host names using [system.net.dns]. If the IP wasn't resolved .Net threw a terminating error. To prevent the terminating error and still retain control of the output, I created a function using TRAP.

E.G.

Function Get-IP 
{PARAM   ([string]$HostName="")
PROCESS {TRAP 
             {"" ;continue} 
             [system.net.dns]::gethostaddresses($HostName)
        }
}
8

Add -ErrorAction SilentlyContinue to your script and you'll be good to go.

3
  • How do you add -ErrorAction SiltentlyContinue to the script? Could you post an example? Jan 4, 2021 at 17:47
  • Using this flag the script can continue without error but error message may still be printed for some commands. For this command it continues and does not print an error message: "$result = Test-Path $path -ErrorAction SilentlyContinue", but for this "$AppPool = Get-WebAppPoolState $sitename -ErrorAction SilentlyContinue" it continues and prints an error message Feb 4, 2021 at 8:21
  • Letting your program continue when the previous action failed is almost always a bad idea. There are very few times when your program can do anything useful after an operation fails.
    – jpmc26
    Aug 28, 2022 at 17:46
8

You're way off track here. Silencing errors is almost never a good idea, and manually checking $? explicitly after every single command is enormously cumbersome and easy to forget to do (error prone). Don't set yourself up to easily make a mistake. If you're getting lots and lots of red, that means your script kept going when it should have stopped instead. It can no longer do useful work if most of its commands are failing. Continuing a program when it and the system are in an unknown state will have unknown consequences; you could easily leave the system in a corrupt state.

The correct solution is to stop the algorithm on the first error. This principle is called "fail fast," and PowerShell has a built in mechanism to enable that behavior. It is a setting called the error preference, and setting it to the highest level will make your script (and the child scopes if they don't override it) behave this way:

$ErrorActionPreference = 'Stop'

This will produce a nice, big error message for your consumption and prevent the following commands from executing the first time something goes wrong, without having to check $? every single time you run a command. This makes the code vastly simpler and more reliable. I put it at the top of every single script I ever write, and you almost certainly should as well.

In the rare cases where you can be absolutely certain that allowing the script to continue makes sense, you can use one of two mechanisms:

  • catch: This is the better and more flexible mechanism. You can wrap a try/catch block around multiple commands, allowing the first error to stop the sequence and jump into the handler where you can log it and then otherwise recover from it or rethrow it to bubble the error up even further. You can also limit the catch to specific errors, meaning that it will only be invoked in specific situations you anticipated rather than any error. (For example, failing to create a file because it already exists warrants a different response than a security failure.)
  • The common -ErrorAction parameter: This parameter changes the error handling for one single function call, but you cannot limit it to specific types of errors. You should only use this if you can be certain that the script can continue on any error, not just the ones you can anticipate.

In your case, you probably want one big try/catch block around your entire program. Then your process will stop on the first error and the catch block can log it before exiting. This will remove a lot of duplicate code from your program in addition to cleaning up your log file and terminal output and making your program less likely to cause problems.

Do note that this doesn't handle the case when external executables fail (exit code nonzero, conventionally), so you do still need to check $LASTEXITCODE if you invoke any. Despite this limitation, the setting still saves a lot of code and effort.

Additional reliability

You might also want to consider using strict mode:

Set-StrictMode -Version Latest

This prevents PowerShell from silently proceeding when you use a non-existent variable and in other weird situations. (See the -Version parameter for details about what it restricts.)

Combining these two settings makes PowerShell much more of fail-fast language, which makes programming in it vastly easier.

5
  • 4
    You claim this makes it more reliable but in the case of any automation it does the opposite. Sometimes there are scripts that should run regardless of whether there's an error with a previous cmdlet and it's much easier to distribute a single powershell script than one per required action. With your solution, if a file that needs to be deleted on startup isn't there (because windows) then none of the later cmdlets in that script will be run despite the system being in the required state. Congrats, you now have a broken script running remotely with errors that aren't being pushed to a log file
    – IAmJersh
    Jul 29, 2021 at 9:37
  • @TheHitchenator The way you handle a file already existing is you write the code to keep going if it exists. You don't need to silence errors for that; you just check if it exists first or use -Force or something else depending on the exact behavior you need. If you just silence errors, your script will keep going when creating the files fails due to security policy, and it will not work correctly and may even corrupt the system further. Letting a broken script continue is far more dangerous than finding out you forgot to handle a particular system state.
    – jpmc26
    Aug 28, 2022 at 17:52
  • 3
    you're literally providing an answer to a question of "how do I disable this error output? I've got my own error checking built into the script" by saying "don't do that, just let the errors block the script instead." Clearly if they've got error checking built into it then they're going to handle these issues. You're not being helpful, just needlessly contrarian because you are failing to envision an environment in which things don't work the way you're used to. Please, when providing answers, actually answer the question rather than just telling someone not to do something.
    – IAmJersh
    Aug 30, 2022 at 9:27
  • @TheHitchenator If the following commands are all failing anyway (as evidenced by the large number of errors the OP is getting), there is no reason to execute them. It has nothing to do with my imagination and everything to do with the evidence given to us. The approach is flawed and creates work and increases the chance of creating problems. No one is served well by being left to continue down a bad path without an alternative. SO has always explicitly encouraged providing better alternative approaches.
    – jpmc26
    Aug 30, 2022 at 16:22
  • @TheHitchenator Also, if you had actually read my answer (both before and after the recent edits), it does explain how to manage errors.
    – jpmc26
    Aug 30, 2022 at 16:23
3

To extend on Mikkel's answer.

If you still want to capture the error, you can use "-ErrorAction stop" combined with a try - catch.

"-ErrorAction silentlycontinue" will ignore the error.

For instance:

try
{
    New-Item -Path "/somepath" -Name "somename" -ErrorAction Stop | Out-Null
}
catch
{
    echo "You must run this command in an elevated mode."
}

NOTE: There is no "silentlyStop" action, and I believe Mickel's answer refers to the "stop" action. It is likely a typo. The idea of using a try-catch combined with the "stop" action is to be able to not just dismiss eventual errors but to show something in case of errors.

2

In some cases you can pipe after the command a Out-Null

command | Out-Null
1
  • This never silences error output, only success output.
    – mklement0
    Jan 17 at 2:36
-1

If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"

4
  • 2
    There is no such action. Altough there is a Stop action. Jul 31, 2015 at 10:30
  • But it allow to suppress red error message and still use catch command/section when using New-Item -ItemType directory (PowerShell v2.0) Sep 13, 2018 at 17:08
  • @MilanKerslager could you kindly show a code sample - since I, and everyone else, believe that there is no such ActionPreference as 'SilentlyStop'
    – FSCKur
    Jan 22, 2019 at 16:48
  • I'm reasonably confident that Mikkel meant SilentlyContinue rather than silentlyStop, because that makes a lot more sense in the content of what you want it to be doing.
    – John
    Mar 21, 2019 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.