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 atry
/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 thecatch
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.
How do you make powershell ignore failures on legacy commands?
All powershell modules support -ErrorAction
, however that does not work with legacy commands like NET STOP
NET STOP WUAUSERV
echo $?
true
I want to attempt to stop the service, and if the service is already stopped, continue. An easy way to reproduce this is to try and stop the service twice.
Things I’ve tried
$ErrorActionPreference = "SilentlyContinue"
NET STOP WUAUSERV
NET STOP WUAUSERV
echo $LASTEXITCODE
Tried using AND and OR operrators
and
NET STOP WUAUSERV || $true
NET STOP WUAUSERV || $true
echo $LASTEXITCODE
or
NET STOP WUAUSERV && $true
NET STOP WUAUSERV && $true
echo $LASTEXITCODE
I’ve also tried redirecting errors
NET STOP WUAUSERV 2>nul
NET STOP WUAUSERV 2>nul
echo $LASTEXITCODE
As recommended in a similar question, I’ve also tried
cmd.exe /C "NET STOP WUAUSERV"
How can I make this legacy command idempotent?
- Remove From My Forums
-
Question
-
Hello All,
How can I remove the warnings from my powershell result output.
I have this warnings in my powershell and I need to remove this from the output, How can I do that?
Regards
Answers
-
-
Marked as answer by
JPFG
Monday, September 23, 2013 10:44 AM
-
Marked as answer by
All replies
-
could you try this option
-WarningAction SilentlyContinue
Satheesh
My Blog-
Edited by
Satheesh Variath
Monday, September 23, 2013 10:01 AM
code
-
Edited by
-
Try to use the -ErrorAction:silentlycontinue or -WarningAction:silentlycontinu parameters ?
You can read more about these if you type help about_Common_Parameters in PowerShell
-
thanks for your help,
The warnings already disapear, but now I have another error, how can I remove this error from my script?
The error is:
Another question, How can I get only the value {Owner} from my result?
Regards
-
-
Marked as answer by
JPFG
Monday, September 23, 2013 10:44 AM
-
Marked as answer by
- Introduction to Error Action in PowerShell
- Use the
-ErrorAction
Parameter in PowerShell - Setting Error Action Preferences in PowerShell
Whether we want to ignore error messages or terminate a script’s execution when an error occurs, Windows PowerShell has plenty of options for dealing with errors. This article will discuss multiple techniques in handling and suppressing errors.
Introduction to Error Action in PowerShell
Even though it is effortless to suppress Windows PowerShell errors, doing so isn’t always the best option (although it can be). If we carelessly tell PowerShell to hide errors, it can cause our script to behave unpredictably.
Suppressing error messages also makes troubleshooting and information gathering a lot more complicated. So tread lightly and be careful about using the following snippets that you will see in this article.
Use the -ErrorAction
Parameter in PowerShell
The most common method for dealing with errors is to append the -ErrorAction
parameter switch to a cmdlet. The -ErrorAction
parameter switch lets PowerShell tell what to do if the cmdlet produces an error.
Command:
Get-Service 'svc_not_existing' -ErrorAction SilentlyContinue
In the command above, we are querying for a service that doesn’t exist. Usually, PowerShell will throw an error if the service doesn’t exist.
Since we use the -ErrorAction
parameter, the script will continue as expected, like it doesn’t have an error.
Setting Error Action Preferences in PowerShell
If we need a script to behave in a certain way (such as suppressing errors), we might consider setting up some preference variables. Preference variables act as configuration settings for PowerShell.
We might use a preference variable to control the number of history items that PowerShell retains or force PowerShell to ask the user before performing specific actions.
For example, here is how you can use a preference variable to set the -ErrorAction
parameter to SilentlyContinue
for the entire session.
Command:
$ErrorActionPreference = 'SilentlyContinue'
There are many other error actions that we can specify for the ErrorAction
switch parameter.
Continue
: PowerShell will display the error message, but the script will continue to run.Ignore
: PowerShell does not produce any error message, writes any error output on the host, and continues execution.Stop
: PowerShell will display the error message and stop running the script.Inquire
: PowerShell displays the error message but will ask for confirmation first if the user wants to continue.SilentlyContinue
: PowerShell silently continues with code execution if the code does not work or has non-terminating errors.Suspend
: PowerShell suspends the workflow of the script.
As previously mentioned, the -ErrorAction
switch has to be used in conjunction with a PowerShell cmdlet. For instance, we used the Get-Process
cmdlet to demonstrate how the ErrorAction
switch works.
Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.
If you own the book already, login here to get free, online, searchable access to the entire book’s content.
If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: «The Windows PowerShell Interactive Shell».
Problem
You want to handle warnings, errors, and terminating errors generated by scripts or other tools that you call.
Solution
To control how your script responds to warning messages, set the $warningPreference
variable. In this example, to ignore them:
$warningPreference
=
"SilentlyContinue"
To control how your script responds to nonterminating errors, set the $errorActionPreference
variable. In this example, to ignore them:
$errorActionPreference
=
"SilentlyContinue"
To control how your script responds to terminating errors, you can use either the try
/catch
/finally
statements or the trap
statement. In this example, we output a message and continue with the script:
try
{
1
/
$null
}
catch
[DivideByZeroException]
{
"Don't divide by zero: $_"
}
finally
{
"Script that will be executed even if errors occur in the try statement"
}
Use the trap
statement if you want its error handling to apply to the entire scope:
trap
[DivideByZeroException]
{
"Don't divide by zero!"
;
continue
}
1
/
$null
Discussion
PowerShell defines several preference variables that help you control how your script reacts to warnings, errors, and terminating errors. As an example of these error management techniques, consider the following script.
##############################################################################
##
## Get-WarningsAndErrors
##
## From PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Demonstrates the functionality of the Write-Warning, Write-Error, and throw
statements
#>
Set-StrictMode
-Version
3
Write-Warning
"Warning: About to generate an error"
Write-Error
"Error: You are running this script"
throw
"Could not complete operation."
For more information about running scripts, see Recipe 1.2.
You can now see how a script might manage those separate types of errors:
PS > $warningPreference = "Continue" PS > Get-WarningsAndErrors WARNING: Warning: About to generate an error Exception: C:\scripts\Get-WarningsAndErrors.ps1:23 Line | 23 | throw "Could not complete operation." | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Could not complete operation.
Once you modify the warning preference, the original warning message gets suppressed. A value of SilentlyContinue
is useful when you’re expecting an error of some sort.
PS > $warningPreference = "SilentlyContinue" PS > Get-WarningsAndErrors Write-Error: Error: You are running this script Exception: C:\scripts\Get-WarningsAndErrors.ps1:23 Line | 23 | throw "Could not complete operation." | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Could not complete operation.
When you modify the error preference, you suppress errors and exceptions as well:
PS > $errorActionPreference = "SilentlyContinue" PS > Get-WarningsAndErrors PS >
In addition to the $errorActionPreference
variable, all cmdlets let you specify your preference during an individual call. With an error action preference of SilentlyContinue
, PowerShell doesn’t display or react to errors. It does, however, still add the error to the $error
collection for futher processing. If you want to suppress even that, use an error action preference of Ignore
.
PS > $errorActionPreference = "Continue" PS > Get-ChildItem IDoNotExist Get-ChildItem : Cannot find path '...\IDoNotExist' because it does not exist. At line:1 char:14 + Get-ChildItem <<<< IDoNotExist PS > Get-ChildItem IDoNotExist -ErrorAction SilentlyContinue PS >
If you reset the error preference back to Continue
, you can see the impact of a try
/catch
/finally
statement. The message from the Write-Error
call makes it through, but the exception does not:
PS > $errorActionPreference = "Continue" PS > try { Get-WarningsAndErrors } catch { "Caught an error" } WARNING: Warning: About to generate an error Get-WarningsAndErrors: Error: You are running this script Caught an error
The try
/catch
/finally
statement acts like the similar statement in other programming languages. First, it executes the code inside of its script block. If it encounters a terminating error, it executes the code inside of the catch
script block. It executes the code in the finally
statement no matter what—an especially useful feature for cleanup or error-recovery code.
A similar technique is the trap
statement:
PS > $errorActionPreference = "Continue" PS > trap { "Caught an error"; continue }; Get-WarningsAndErrors WARNING: Warning: About to generate an error Get-WarningsAndErrors: Error: You are running this script Caught an error
Within a catch
block or trap
statement, the $_
(or $PSItem
) variable represents the current exception or error being processed.
Unlike the try
statement, the trap
statement handles terminating errors for anything in the scope that defines it. For more information about scopes, see Recipe 3.6.
Note
After handling an error, you can also remove it from the system’s error collection by typing $error.RemoveAt(0)
.
For more information about PowerShell’s automatic variables, type Get-Help about
_automatic_variables
. For more information about error management in PowerShell, see “Managing Errors”. For more detailed information about the valid settings of these preference variables, see Appendix A.
See Also
Recipe 1.2, “Run Programs, Scripts, and Existing Tools”
Recipe 3.6, “Control Access and Scope of Variables and Other Items”
“Managing Errors”
Appendix A, PowerShell Language and Environment