Powershell error clear

Is there a way to clear the $Error variable that tracks errors in a PowerShell session? If so, how do you do it? I have tried: $error.clear In the PowerShell ISE on Windows 7 and the $Error arra...
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Ask Question

Asked
13 years, 3 months ago

Modified
7 years, 2 months ago

Viewed
74k times

69

Is there a way to clear the $Error variable that tracks errors in a PowerShell session?

If so, how do you do it?

I have tried:
$error.clear

In the PowerShell ISE on Windows 7 and the $Error array is still populated.

  • powershell

Improve this question

edited Nov 11, 2009 at 17:32

Matt Spradley

asked Nov 11, 2009 at 17:13

Matt Spradley's user avatar

Matt SpradleyMatt Spradley

7,6249 gold badges30 silver badges40 bronze badges

Add a comment
 | 

1 Answer

Sorted by:

Reset to default

127

It is a .NET method call so you need parens:

$error.clear()

Improve this answer

answered Nov 11, 2009 at 17:42

Keith Hill's user avatar

Keith HillKeith Hill

190k40 gold badges344 silver badges365 bronze badges

3

  • 20

    PowerShell is not case-sensitive. If it were, it would be $Error.Clear(). :-)

    – Keith Hill

    Nov 8, 2013 at 20:55

  • 1

    Shouldn’t you preserve case if you can though?

    – n00dles

    Aug 23, 2020 at 20:36

  • @n00dles The linked article is about designing cmdlets to treat case appropriately. It is not about case throughout the use of PowerShell. It does not matter for the majority of commands you give it. $eRRor.CLEAR() is fine.

    – C Perkins

    Apr 29, 2022 at 15:02

Add a comment
 | 

Your Answer

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged

  • powershell

or ask your own question.

  • The Overflow Blog
  • Engineering’s hidden bottleneck: pull requests

    sponsored post

  • Three layers to secure a software development organization

  • Featured on Meta
  • Accessibility Update: Colors

  • Collectives: The next iteration

  • Temporary policy: ChatGPT is banned

  • We’ve made changes to our Privacy Notice for Collectives™

Related

899

Setting Windows PowerShell environment variables

2813

Determine installed PowerShell version

524

Terminating a script in PowerShell

942

How to run a PowerShell script

589

How to handle command-line arguments in PowerShell

2703

PowerShell says «execution of scripts is disabled on this system.»

208

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

872

How do I concatenate strings and variables in PowerShell?

243

Reload the path in PowerShell

289

How to create permanent PowerShell Aliases

Hot Network Questions

  • Converting an older motor to ethanol has significant risk of damage?

  • What is the ampersand sign (&) before commands in PowerShell?

  • Why do Presidential flights have special call signs?

  • Why is 1Password sign-in to new device secure without MFA?

  • Is there a word for ‘evangelism’ that doesn’t necessarily specify the religion?

  • How to stop water runoff on floating islands that lack an available surface

  • Fair scoring system for multiple levels and multiple players

  • Human oriented string comparison

  • A curve line with label connecting two tabular cells with TikZ

  • Generic solution for how to deal with overfull hbox vs alternative solutions

  • .ssh Directory has no id files after installing ssh service

  • Does a hexapedal mech move quicker when it’s closer to the ground and the legs are spread out or is it the opposite?

  • At what point is it «legal» to overthrow the government?

  • Do astronauts use plumber’s bifocals?

  • What is the name of the pedal assembly in an aircraft cockpit?

  • when using a chromatic mediant chord in a minor piece which accidental do you use?

  • Is SQL Server able to use internal parallelism for an update statement?

  • I’m new to D&D: where to begin?

  • Why did so few militaries use semi automatic rifles as their standard issue infantry weapon?

  • Threading arguments from lists of different size

  • How to fix unwanted deform when animating model

  • Djinn in modern times

  • How much would a slave cost in current day Europe?

  • Mesh shading problem with shade smooth

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Asked
13 years, 3 months ago

Viewed
74k times

Is there a way to clear the $Error variable that tracks errors in a PowerShell session?

If so, how do you do it?

I have tried:
$error.clear

In the PowerShell ISE on Windows 7 and the $Error array is still populated.

  • powershell

asked Nov 11, 2009 at 17:13

Matt Spradley's user avatar

Matt SpradleyMatt Spradley

7,6249 gold badges30 silver badges40 bronze badges

1 Answer

It is a .NET method call so you need parens:

$error.clear()

answered Nov 11, 2009 at 17:42

Keith Hill's user avatar

Keith HillKeith Hill

190k40 gold badges344 silver badges365 bronze badges

3

  • PowerShell is not case-sensitive. If it were, it would be $Error.Clear(). :-)

    Nov 8, 2013 at 20:55

  • Shouldn’t you preserve case if you can though?

    Aug 23, 2020 at 20:36

  • @n00dles The linked article is about designing cmdlets to treat case appropriately. It is not about case throughout the use of PowerShell. It does not matter for the majority of commands you give it. $eRRor.CLEAR() is fine.

    Apr 29, 2022 at 15:02

  • The Overflow Blog
  • Featured on Meta

Related

Hot Network Questions

  • UK visa requirement abolished for Colombian citizens, but what needs to be shown at border for 3 month stay?

  • Added an eye for the Newman projection

  • How to temporarily catch leaks trickling down the outside of a pipe

  • Mesh shading problem with shade smooth

  • Comparative analysis of history of mathematics

  • screwed up a talk

  • Creating dieline for inkjet printing

  • What do you think about something like coumpound syscalls?

  • Merge multiple map with java stream api

  • Is there a word for ‘evangelism’ that doesn’t necessarily specify the religion?

  • Making new field with formatted values without leading zeros in QGIS

  • Why is mind interacting with matter any more problematic than matter interacting with matter?

  • Why all the warnings about failure to raise the U.S. debt ceiling when some argue that Biden could just ignore it?

  • How to make bitcoin hd wallet in typescript?

  • A curve line with label connecting two tabular cells with TikZ

  • When targeted by a Nightwalker, can a Monk get rid of Finger of Doom effect by using Stillness of Mind?

  • What’s the name of this poem in Danya Ruttenberg’s «Surprised by God»?

  • Djinn in modern times

  • Are there any examples of orienteering (off-trail) route-finding software?

  • Does a gas pressure test lose pressure without leaks?

  • Are there other countries besides Türkiye that insist their name be written in English using diacritics (or even other letters) not common in English?

  • When and where did «perk» become the common shortened form of «perquisite»?

  • How to stop water runoff on floating islands that lack an available surface

  • Is a one hour and a half layover enough time to go through customs?

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Note: This tip requires PowerShell 2.0 or above.

PowerShell has the $error automatic variable. It contains a collection of the errors that occurred while the PowerShell engine has been running. The collection in $error is an instance of System.Collections.ArrayList. The most recent error is the first error object in a collection–$Error[0]. The number of errors that are retained is controlled by the $MaximumErrorCount preference variable (set to 256 by default). You can increase that number up to 32768, but that would increase the memory usage as well. Default value is usually big enough.

What to do if you want to clean out all the entries in $error? $error is a variable, so you can try with the Clear-Variable cmdlet:

PS> Clear-Variable error -Force
Clear-Variable : Cannot overwrite variable Error because it is read-only or constant.

Unfortunately, that doesn’t work even when you use the -Force parameter.

$error is also an object, so maybe the Get-Member cmdlet will reveal a useful method:

PS> $error | Get-Member
   TypeName: System.Management.Automation.ErrorRecord
Name                  MemberType     Definition
----                  ----------     ----------
Equals                Method         bool Equals(System.Object obj)
GetHashCode           Method         int GetHashCode()
GetObjectData         Method         void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System....
GetType               Method         type GetType()
ToString              Method         string ToString()
writeErrorStream      NoteProperty   System.Boolean writeErrorStream=True
CategoryInfo          Property       System.Management.Automation.ErrorCategoryInfo CategoryInfo {get;}
ErrorDetails          Property       System.Management.Automation.ErrorDetails ErrorDetails {get;set;}
Exception             Property       System.Exception Exception {get;}
FullyQualifiedErrorId Property       string FullyQualifiedErrorId {get;}
InvocationInfo        Property       System.Management.Automation.InvocationInfo InvocationInfo {get;}
PipelineIterationInfo Property       System.Collections.ObjectModel.ReadOnlyCollection[int] PipelineIterationInfo {g...
ScriptStackTrace      Property       string ScriptStackTrace {get;}
TargetObject          Property       System.Object TargetObject {get;}
PSMessageDetails      ScriptProperty System.Object PSMessageDetails {get=& { Set-StrictMode -Version 1; $this.Except...

This approach doesn’t work either, because you are getting information about the error objects (System.Management.Automation.ErrorRecord type) contained in the $error variable, not the members of the $error itself. Do you remember our previous tip #PSTip Getting information about a collection object, not its elements? Yes, you need to use -InputObject parameter. You can easily spot the Clear() method now:

PS> Get-Member -InputObject $error
   TypeName: System.Collections.ArrayList

Name           MemberType            Definition
----           ----------            ----------
Add            Method                int Add(System.Object value), int IList.Add(System.Object value)
AddRange       Method                void AddRange(System.Collections.ICollection c)
BinarySearch   Method                int BinarySearch(int index, int count, System.Object value, System.Collections....
Clear          Method                void Clear(), void IList.Clear()
Clone          Method                System.Object Clone(), System.Object ICloneable.Clone()
Contains       Method                bool Contains(System.Object item), bool IList.Contains(System.Object value)
...
...

You could clean out all the entries in $error by calling $error.Clear().

Share on:

Controlling Error Reporting Behavior and Intercepting Errors

This section briefly demonstrates how to use each of PowerShell’s statements, variables and parameters that are related to the reporting or handling of errors.

The $Error Variable

$Error is an automatic global variable in PowerShell which always contains an ArrayList of zero or more ErrorRecord objects. As new errors occur, they are added to the beginning of this list, so you can always get information about the most recent error by looking at $Error[0]. Both Terminating and Non-Terminating errors will be contained in this list.

Aside from accessing the objects in the list with array syntax, there are two other common tasks that are performed with the $Error variable: you can check how many errors are currently in the list by checking the $Error.Count property, and you can remove all errors from the list with the $Error.Clear() method. For example:

image004.png

Figure 2.1: Using $Error to access error information, check the count, and clear the list.

If you’re planning to make use of the $Error variable in your scripts, keep in mind that it may already contain information about errors that happened in the current PowerShell session before your script was even started. Also, some people consider it a bad practice to clear the $Error variable inside a script; since it’s a variable global to the PowerShell session, the person that called your script might want to review the contents of $Error after it completes.

ErrorVariable

The ErrorVariable common parameter provides you with an alternative to using the built-in $Error collection. Unlike $Error, your ErrorVariable will only contain errors that occurred from the command you’re calling, instead of potentially having errors from elsewhere in the current PowerShell session. This also avoids having to clear the $Error list (and the breach of etiquette that entails.)

When using ErrorVariable, if you want to append to the error variable instead of overwriting it, place a + sign in front of the variable’s name. Note that you do not use a dollar sign when you pass a variable name to the ErrorVariable parameter, but you do use the dollar sign later when you check its value.

The variable assigned to the ErrorVariable parameter will never be null; if no errors occurred, it will contain an ArrayList object with a Count of 0, as seen in figure 2.2:

image005.png

Figure 2.2: Demonstrating the use of the ErrorVariable parameter.

$MaximumErrorCount

By default, the $Error variable can only contain a maximum of 256 errors before it starts to lose the oldest ones on the list. You can adjust this behavior by modifying the $MaximumErrorCount variable.

ErrorAction and $ErrorActionPreference

There are several ways you can control PowerShell’s handling / reporting behavior. The ones you will probably use most often are the ErrorAction common parameter and the $ErrorActionPreference variable.

The ErrorAction parameter can be passed to any Cmdlet or Advanced Function, and can have one of the following values: Continue (the default), SilentlyContinue, Stop, Inquire, Ignore (only in PowerShell 3.0 or later), and Suspend (only for workflows; will not be discussed further here.) It affects how the Cmdlet behaves when it produces a non-terminating error.

  • The default value of Continue causes the error to be written to the Error stream and added to the $Error variable, and then the Cmdlet continues processing.
  • A value of SilentlyContinue only adds the error to the $Error variable; it does not write the error to the Error stream (so it will not be displayed at the console).
  • A value of Ignore both suppresses the error message and does not add it to the $Error variable. This option was added with PowerShell 3.0.
  • A value of Stop causes non-terminating errors to be treated as terminating errors instead, immediately halting the Cmdlet’s execution. This also enables you to intercept those errors in a Try/Catch or Trap statement, as described later in this section.
  • A value of Inquire causes PowerShell to ask the user whether the script should continue or not when an error occurs.

The $ErrorActionPreference variable can be used just like the ErrorAction parameter, with a couple of exceptions: you cannot set $ErrorActionPreference to either Ignore or Suspend. Also, $ErrorActionPreference affects your current scope in addition to any child commands you call; this subtle difference has the effect of allowing you to control the behavior of errors that are produced by .NET methods, or other causes such as PowerShell encountering a «command not found» error.

Figure 2.3 demonstrates the effects of the three most commonly used $ErrorActionPreference settings.

image006.png

Figure 2.3: Behavior of $ErrorActionPreference

Try/Catch/Finally

The Try/Catch/Finally statements, added in PowerShell 2.0, are the preferred way of handling terminating errors. They cannot be used to handle non-terminating errors, unless you force those errors to become terminating errors with ErrorAction or $ErrorActionPreference set to Stop.

To use Try/Catch/Finally, you start with the «Try» keyword followed by a single PowerShell script block. Following the Try block can be any number of Catch blocks, and either zero or one Finally block. There must be a minimum of either one Catch block or one Finally block; a Try block cannot be used by itself.

The code inside the Try block is executed until it is either complete, or a terminating error occurs. If a terminating error does occur, execution of the code in the Try block stops. PowerShell writes the terminating error to the $Error list, and looks for a matching Catch block (either in the current scope, or in any parent scopes.) If no Catch block exists to handle the error, PowerShell writes the error to the Error stream, the same thing it would have done if the error had occurred outside of a Try block.

Catch blocks can be written to only catch specific types of Exceptions, or to catch all terminating errors. If you do define multiple catch blocks for different exception types, be sure to place the more specific blocks at the top of the list; PowerShell searches catch blocks from top to bottom, and stops as soon as it finds one that is a match.

If a Finally block is included, its code is executed after both the Try and Catch blocks are complete, regardless of whether an error occurred or not. This is primarily intended to perform cleanup of resources (freeing up memory, calling objects’ Close() or Dispose() methods, etc.)

Figure 2.4 demonstrates the use of a Try/Catch/Finally block:

image007.png

Figure 2.4: Example of using try/catch/finally.

Notice that «Statement after the error» is never displayed, because a terminating error occurred on the previous line. Because the error was based on an IOException, that Catch block was executed, instead of the general «catch-all» block below it. Afterward, the Finally executes and changes the value of $testVariable.

Also notice that while the Catch block specified a type of [System.IO.IOException], the actual exception type was, in this case, [System.IO.DirectoryNotFoundException]. This works because DirectoryNotFoundException is inherited from IOException, the same way all exceptions share the same base type of System.Exception. You can see this in figure 2.5:

image008.png

Figure 2.5: Showing that IOException is the Base type for DirectoryNotFoundException

Trap

Trap statements were the method of handling terminating errors in PowerShell 1.0. As with Try/Catch/Finally, the Trap statement has no effect on non-terminating errors.

Trap is a bit awkward to use, as it applies to the entire scope where it is defined (and child scopes as well), rather than having the error handling logic kept close to the code that might produce the error the way it is when you use Try/Catch/Finally. For those of you familiar with Visual Basic, Trap is a lot like «On Error Goto». For that reason, Trap statements don’t see a lot of use in modern PowerShell scripts, and I didn’t include them in the test scripts or analysis in Section 3 of this ebook.

For the sake of completeness, here’s an example of how to use Trap:

image009.png

Figure 2.6: Use of the Trap statement

As you can see, Trap blocks are defined much the same way as Catch blocks, optionally specifying an Exception type. Trap blocks may optionally end with either a Break or Continue statement. If you don’t use either of those, the error is written to the Error stream, and the current script block continues with the next line after the error. If you use Break, as seen in figure 2.5, the error is written to the Error stream, and the rest of the current script block is not executed. If you use Continue, the error is not written to the error stream, and the script block continues execution with the next statement.

The $LASTEXITCODE Variable

When you call an executable program instead of a PowerShell Cmdlet, Script or Function, the $LASTEXITCODE variable automatically contains the process’s exit code. Most processes use the convention of setting an exit code of zero when the code finishes successfully, and non-zero if an error occurred, but this is not guaranteed. It’s up to the developer of the executable to determine what its exit codes mean.

Note that the $LASTEXITCODE variable is only set when you call an executable directly, or via PowerShell’s call operator (&) or the Invoke-Expression cmdlet. If you use another method such as Start-Process or WMI to launch the executable, they have their own ways of communicating the exit code to you, and will not affect the current value of $LASTEXITCODE.

image010.png

Figure 2.7: Using $LASTEXITCODE.

The $? Variable

The $? variable is a Boolean value that is automatically set after each PowerShell statement or pipeline finishes execution. It should be set to True if the previous command was successful, and False if there was an error.
When the previous command was a PowerShell statement, $? will be set to False if any errors occurred (even if ErrorAction was set to SilentlyContinue or Ignore).
If the previous command was a call to a native exe, $? will be set to False if the $LASTEXITCODE variable does not equal zero. If the $LASTEXITCODE variable equals zero, then in theory $? should be set to True. However, if the native command writes something to the standard error stream then $? could be set to False even if $LASTEXITCODE equals zero. For example, the PowerShell ISE will create and append error objects to $Error for standard error stream output and consequently $? will be False regardless of the value of $LASTEXITCODE. Redirecting the standard error stream into a file will result in a similar behavior even when the PowerShell host is the regular console. So it is probably best to test the behavior in your specific environment if you want to rely on $? being set correctly to True.

Just be aware that the value of this variable is reset after every statement. You must check its value immediately after the command you’re interested in, or it will be overwritten (probably to True). Figure 2.8 demonstrates this behavior. The first time $? is checked, it is set to False, because the Get-Item encountered an error. The second time $? was checked, it was set to True, because the previous command was successful; in this case, the previous command was «$?» from the first time the variable’s value was displayed.

image011.png

Figure 2.8: Demonstrating behavior of the $? variable.

The $? variable doesn’t give you any details about what error occurred; it’s simply a flag that something went wrong. In the case of calling executable programs, you need to be sure that they return an exit code of 0 to indicate success and non-zero to indicate an error before you can rely on the contents of $?.

Summary

That covers all of the techniques you can use to either control error reporting or intercept and handle errors in a PowerShell script. To summarize:

  • To intercept and react to non-terminating errors, you check the contents of either the automatic $Error collection, or the variable you specified as the ErrorVariable. This is done after the command completes; you cannot react to a non-terminating error before the Cmdlet or Function finishes its work.
  • To intercept and react to terminating errors, you use either Try/Catch/Finally (preferred), or Trap (old and not used much now.) Both of these constructs allow you to specify different script blocks to react to different types of Exceptions.
  • Using the ErrorAction parameter, you can change how PowerShell cmdlets and functions report non-terminating errors. Setting this to Stop causes them to become terminating errors instead, which can be intercepted with Try/Catch/Finally or Trap.
  • $ErrorActionPreference works like ErrorAction, except it can also affect PowerShell’s behavior when a terminating error occurs, even if those errors came from a .NET method instead of a cmdlet.
  • $LASTEXITCODE contains the exit code of external executables. An exit code of zero usually indicates success, but that’s up to the author of the program.
  • $? can tell you whether the previous command was successful, though you have to be careful about using it with external commands. If they don’t follow the convention of using an exit code of zero as an indicator of success or if they write to the standard error stream then the resulting value in $? may not be what you expect. You also need to make sure you check the contents of $? immediately after the command you are interested in.

Для начала определимся, что такое обработка ошибок вообще. В общем случае ошибка — это поведение программы или скрипта, отличное от запланированного. Совсем избежать ошибок не очень возможно, поэтому надо предвидеть, где они могут возникнуть и писать код так, чтобы при возникновении ошибки можно было перехватить ее, проанализировать и определить дальнейшее поведение скрипта.  Именно это обычно и подразумевается под обработкой ошибок.

В PowerShell ошибки делятся на два типа: прерывающие (Terminating) и непрерывающие (Non-Terminating). Как следует из названия, непрерывающие ошибки позволяют продолжить выполнение команды, тогда как при возникновении прерывающей ошибки дальнейшее продолжение выполнения команды невозможно. К примеру, у нас есть файл со списком служб, которые необходимо перезапустить следующей командой:

Get-Content -Path C:Filesservices.txt | Restart-Service

Предположим, что перезапуск одной из перечисленных служб по какой либо причине невозможен. Тем не менее можно продолжать выполнение задачи, поскольку остальные службы доступны и их можно перезапустить. Это пример непрерывающей ошибки.

А теперь представьте, что у нас нет прав на открытие этого файла, и соответственно прочитать список служб мы не можем. В этой ситуации продолжение работы невозможно, т.е. это прерывающая ошибка.

PowerShell позволяет обрабатывать оба эти типа ошибок. Большинство ошибок в PowerShell непрерывающие, и сегодня речь пойдет о том, как их обрабатывать.

Обработка непрерывающих ошибок

Для получения ошибки возьмем службу с ″оригинальным″ названием Service. Поскольку службы этой на сервере нет, то обращение к ней стабильно будет генерировать ошибку. Запросим данные о нескольких службах командой:

Get-Service service,spooler

Как видно из примера, PowerShell не нашел службу Service, о чем выдал ошибку и затем продолжил выполнение команды. Давайте разберемся, почему команда повела себя именно так и как это поведение изменить.

обработка ошибки по умолчанию

За поведение команды при возникновении ошибки отвечает параметр ErrorAction, который может принимать одно из пяти значений:

• Continue;
• SilentlyContinue;
• Stop;
• Ignore;
• Inquire.

Примечание. Еще у ErrorAction может быть значение Suspend. Но это значение может применяться только к рабочим процессам (workflows), поэтому в рамках данной статьи речь о нем не пойдет.

Значение Continue означает, что при возникновении ошибки информация об этом будет выведена на экран (отправлена в поток вывода Error) и добавлена в автоматическую переменную $Error, после чего выполнение команды будет продолжено. Надо сказать, что Continue — это действие, определенное в сеансе по умолчанию, поэтому его можно не указывать явно.

обработка ошибки, режим Continue

При значении SilentlyContinue информация об ошибке добавляется в переменную $Error, но не выводится на экран. При этом команда продолжает выполняться дальше, также как и в предыдущем случае.

обработка ошибки, режим SilentlyContinue

Значение Stop останавливает дальнейшее выполнение команды при возникновении ошибки. И наоборот, значение Ignore полностью игнорирует возникновение ошибки, при этом не выводится сообщение на экран и не производится запись в $Error. Это значение появилось в PowerShell 3.0.

Обработка ошибок в режимах Stop и Ignore

Inquire — наиболее интересное значение ErrorAction. Если задать это значение, то при возникновении ошибки предлагается на выбор несколько действий: продолжить (Yes), продолжить не смотря на эту и все последующие ошибки (Yes to All), остановить (Halt) или приостановить (Suspend) выполнение команды.

Самый необычный эффект дает Suspend, при выборе которого открывается параллельный сеанс (Nested Namespace). Определить его можно по значку >>. Nested Namespace представляет из себя дочерний процесс, в котором можно полноценно работать — выполнять команды, запускать скрипты и т.п. Этот режим удобно использовать для отладки скриптов, например можно по быстрому исправить причину ошибки и продолжить выполнение. Для выхода из Nested Namespace достаточно набрать exit и выбрать необходимое действие.

Обработка ошибки в режиме Inquire

Примечание. У параметра ErrorAction есть алиас — EA. Кроме того, вместо названия параметра можно указывать числовые значения: 0 (SilentlyContinue), 1 (Stop), 2 (Continue), 3 (Inquire). Так например, вместо:

Get-Service service,spooler -ErrorAction SilentlyContinue

можно написать так:

Get-Service service,spooler -EA 0

Переменные для обработки ошибок

Как я уже говорил, если не указывать параметр ErrorAction, то для команды действует режим обработки ошибок, определенный в сеансе. Этот режим задается переменной $ErrorActionPreference, которая по умолчанию имеет значение Continue. При желании можно переопределить режим для всего сеанса, задав переменной $ErrorActionPreference нужное значение.

Политика обработки ошибок по умолчанию

Все ошибки PowerShell сохраняет в автоматическую переменную $Error. Это глобальная переменная, которая представляет из себя массив строк, содержащий записи обо всех ошибках в текущем сеансе. Каждая новая ошибка добавляется в начало массива, соответственно для просмотра последней ошибки надо обратиться к самому первому элементу массива $Error[0].

$Error имеет свои свойства и методы, которые можно использовать. Например, посмотреть общее количество ошибок в текущем сеансе можно командой $Error.Count, а очистить список — командой $Error.Clear().

переменная $Error

Переменная $Error не безразмерна, по умолчанию она хранит не более 256 ошибок. При превышении этого количества наиболее старые ошибки будут затираться. При необходимости количество записей в переменной $Error можно увеличить, изменив значение другой переменной $MaximumErrorCount.

Кроме $Error для хранения ошибок допускается задавать собственные переменные. Сделать это можно с помощью параметра ErrorVariable, например так:

Get-Service service,spooler -ErrorAction SilentlyContinue -ErrorVariable var

Обратите внимание, что имя переменной в команде задается без знака $, хотя в дальнейшем к ней обращаемся как к обычной переменной $var.

назначение собственной переменной для хранения ошибок

В отличие от глобальной переменной $Error заданные вручную переменные хранят только ошибки той команды, в которой они определены. Кроме того, по умолчанию эти переменные каждый раз перезаписываются и поэтому хранят только последнюю ошибку. Если вы хотите, чтобы новые ошибки добавлялись в переменную, не перезаписывая ее содержимое, то перед именем переменной надо поставить знак +, например +var.

Пока все, а в следующей части пойдет о способах обработки прерывающих ошибок.

Are you trying to resolve PowerShell $Error clear?

This guide will help you.

The $Error is a variable in the PowerShell which contains information about the error messages.

If we use $Error variable in the scripts it may already contain information about errors before the script starts.

So to avoid this we have to clear the error in $Error variable before executing the script.

To create a new variable, use an assignment statement to assign a value to the variable. You don’t have to declare the variable before using it. The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable .

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform PowerShell related queries.

In this context, we shall look into the nature of PowerShell $Error variable and steps to resolve it.

How to use the PowerShell $Error clear option?

Before going to the details of using $Error we will take a glimpse at what is $Error.

What is PowerShell $Error?

The $Error is a variable in PowerShell that contains an Array List of zero or Error Record objects.

If we enter a wrong command in the Windows PowerShell, the error is recorded in the $Error variable.

The different options provided by the $Error variable are:

i. $Error.Count – It checks the number of errors currently on the list.

ii. $Error[0] – It provides information about the most recent errors.

iii. $Error.Clear() – It removes all errors from the list.

How to use the PowerShell $Error clear option ?

Here you will learn more about how $Error option works in detail.

Whenever the PowerShell session starts, initially the $Error variable does not contain anything.

The $Error variable stores the error object when we type a wrong command.

For example, if we type the wrong command Ip[onfig instead of ipconfig then the $Error variable will increase.

To display the information of the error we can use  $Error[0] command.

Also, we can easily clear the errors in the $Error variable by running the below command:

$Error.Clear()

We have to keep in mind that we must always call the command with parenthesis otherwise it will not work.

If we do not clear $Error it will be difficult to differentiate whether the error is generated by the script or the incorrect command.

[Need urgent assistance with PowerShell $Error clear? — We’re available 24/7. ]

Errors in your PowerShell script can stop the execution of your script, but sometimes that is completely unnecessary. Try Catch blocks in PowerShell help you to handle those errors properly.

Take the following example; You need to update the job titles of 20 employees. The HR department has given you a list with names and the new job titles, but they misspelled one of the names.

Without a PowerShell Try Catch block, your script would stop somewhere in the middle, leaving you with half the records updated. You will now need to figure out where the script has stopped and which user triggered the error.

With Try Catch in PowerShell, we can process the whole list and write a proper error message (or even send an email) when something is wrong.

In this article, we are going to take a look at how to use Try, Catch, Finally in PowerShell and how to find the correct error message to catch.

Let’s first take a look at the basics of the Try Catch Finally block. A Try Catch block in Powershell always exists of one Try block and atleast one Catch block. The Finally block is optional, the code in this block will always run, no matter the outcome of the Try block.

Try
{
    # Try something that could cause an error
    1/0
}
Catch
{
    # Catch any error
    Write-Host "An error occurred"
}
Finally
{
    # [Optional] Run this part always
    Write-Host "cleaning up ..."
}

In the Try block, you place the script that could cause an error. Keep this part small and don’t combine too many functions into it. The goal with a PowerShell Try Catch block is to implement proper error handling, and you can only do that when you Try one tricky function at a time.

If we take the following (simplified) example to update the job titles:

Try{
	# Find the user to update
	$ADUser = Get-AzureAdUser -SearchString $user.name

	# Update the job title
	Set-AzureAdUser -ObjectId $ADUser.ObjectId -JobTitle $user.jobtitle

	# Send an email that the job title is updated
	Send-MailMessage -SmtpServer $smtp.address -To $user.mail -From $smtp.from -Subject $smtp.subject -Body "Your jobtitle is updated"
}
Catch{
	Write-Host ("Failed to update " + $($user.name)) -ForegroundColor Red
}

The problem here is that if something goes wrong in the Try block, we only get an error that the update is failed. But you don’t know which part. Maybe the user is updated but was the script unable to send to mail.

A better option here is to split the Try into finding and updating the user and create another function with a Try-Catch to send the email.

PowerShell Finally block

The finally block is optional, so you don’t need to use it every time. Code inside the finally block is always executed, no matter the outcome of the Try block. You can use the finally block to close a connection for example, or as part of your logging.

Catching Terminating and non-terminating Errors

When it comes to catching errors in PowerShell, there is one thing really important, non-terminating errors. These are errors that won’t terminate (stop) the script. These kinds of errors can’t be caught with a catch block by default.

Most cmdlets in PowerShell are non-terminating. They will output an error, which you will see in red in your console, if you use them wrong, but they won’t stop the script. The reason for this the default ErrorAction in your PowerShell profile, which is set to Continue.

# To show your default error action type
$ErrorActionPreference

Take the following example, opening a non-existing directory in PowerShell with a Try Catch block:

Try {
    dir "c:somenon-existingpath"
    
}
Catch {
    Write-host "Directory does not exist"
}

You expect to the see “Directory does not exist”, but instead you get the normal red error message. The reason for this is that the non-existing path isn’t a terminating error, and the default error action is to continue.

To catch the error you will need toadd the -ErrorAction Stop parameter behind your action.

Try {
    dir "c:somenon-existingpath" -ErrorAction stop
    
}
Catch {
    Write-host "Directory does not exist"
}

Another option is to change the ErrorActionPreference at the beginning of your script or PowerShell session. But keep in mind that the preference will reset to continue when you start a new session.

$ErrorActionPreference = "Stop"

Powershell Try Catch Exception

Exceptions in PowerShell allow you to handle errors even better. Until now we just used a simple catch, that will basically catch any errors. A good way to start, but if you want to improve your PowerShell error handling even further, then you can use Exceptions.

As I mentioned in the beginning, a Try Catch block should have atleast one catch block. That means that we can have multiple catch blocks to catch different errors and handle them differently.

If we take the following example with updating the job titles:

Try{
	# Find the user to update
	$ADUser = Get-AzureAdUser -ObjectId $user.UserPrincipalName -ErrorAction Stop

	# Update the job title
	Set-AzureAdUser -ObjectId $ADUser.ObjectId -JobTitle $user.jobtitle -ErrorAction Stop
}
Catch [Microsoft.Open.Azure.AD.CommonLibrary.AadNeedAuthenticationException]{
	# Catch a connection error
	Write-Warning "You need to Connect to AzureAD first"
}
Catch [Microsoft.Open.AzureAD16.Client.ApiException] {
	# Catch the when we are unable to find the user
	Write-Warning "Unable to find the user"
}
Catch {
	Write-Warning "An other error occured"
}

What we can do here, for example, catch the error when the connection to AzureAD hasn’t been made yet, or the error when we are unable to find the user in the AzureAD. We do this by defining an exception to a catch block.

The difficult part here is finding the exception that you need to catch. The only way to find them is to run your script, and make sure you trigger the error that you want to catch. You can then find the exception in the error message or in the $Error variable

powershell try catch

As you can see in the screenshot, we can find the Authentication exception in the error message (1). Another option is to take a look at the $Error variable. If you run $Error[0].Exception.GetType().FullName directly after the error, then you will get the full exception name that you can use in the catch block.

Powershell Error Variable

Let’s explain a bit more about the PowerShell Error variable. When an error occurs in PowerShell it will be appended to the $error variable. This variable will contain all the errors that occurred during your PowerShell session.

Instead of $error, you can also use $._ or $PSitem inside the catch block to show details about the error.

The $error variable is really useful and contains a lot of information about the error. We can not only use this information to handle the error properly but also to inform the user better.

Finding the location of the error

When you are writing a larger script, it’s handy to know the exact location of the function that causes the error. In the error variable, you will find the ScriptStackTrace. This will output the exact location of the error and the origin.

Take the following example:

$ErrorActionPreference = "Stop"


Function OpenPath($path) {
    Try {
        dir $path 
    }
    Catch {
        Write-host "Directory does not exist" -ForegroundColor Red
        Write-Host $_.ScriptStackTrace
    }
}

OpenPath("c:somenon-existingpath")

When you run this code you will get the following stack trace:

powershell try catch error handling

As you can the error occured on line 6, in the OpenPath function, which was called by the script on line 15.

This kind of information can really help you with debugging your scripts.

Show Proper Error Messages

You can write your own error messages in the PowerShell Catch blocks, but sometimes the exception messages are more than enough.

Function OpenPath($path) {
    Try {
        dir $path -ErrorAction Stop
    }
    Catch {
        Write-Host $_.Exception.Message -ForegroundColor Red
    }
}

#Outputs:
Cannot find path 'C:somenon-existingpath' because it does not exist.

Couting Errors in PowerShell

A small feature of the Error variable, but sometime really handy, counting how many error occurred

$Error.count

Clearing the PowerShell Error Variable

The error variable contains a lot of information, you can see all properties of the Error variable by using the get-member cmdlet. The last thing I want to point out is clearing the error variable. When you are trying to find the correct exception it’s really handy to clear the variable before you run your script again.

$Error.clear()

Wrapping up

Try Catch blocks in PowerShell helps you to write better scripts, scripts that do what you want, even if something goes wrong. The hardest part is writing good catch blocks, because you will need to figured out what can possibly go wrong with your script.

I hope this article helped you to get started with the Try-Catch blocks, if you have any questions, just drop a comment below.

You may also like the following articles:

  • Connect to Exchange Online with PowerShell
  • Enable MFA for Office 365 User with PowerShell
  • Remove From My Forums
  • Question

  • Hello,

    I have a global misunderstanding about error handling. If I start some cmdlet that repeats some steps (classic pipeline for example) and one instance here drops an error but I want to ignore this error why cannot I do this:

        $error.Clear()
        Get-ChildItem ${env:ProgramFiles(x86)} -ErrorVariable $null -ErrorAction SilentlyContinue -Recurse | Where-Object {$_.Name -match "1.exe"} 
        $error[0]

    The error always shows:

    Get-ChildItem : Access to the path ‘C:Program Files (x86)GoogleCrashReports’ is denied.
    At line:2 char:5
    +     Get-ChildItem ${env:ProgramFiles(x86)} -ErrorVariable $null -Erro …
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (C:Program File…leCrashReports:String) [Get-ChildItem], UnauthorizedAccessException
        + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

Answers

  •  if there was an issue while executing of this cmdlet I need to know it without using the $error.Clear() before this cmdlet. 

    I think I see what you’re trying to do. The «bad» answer is to pair a $error.removeat(0) with a try/catch block. That preserves $error[0] for you. A better answer would be to use a different error variables for each command where you need to trap
    errors. 

    That depends on what the rest of your code does. I would think that you would want to examine
    all of the errors in the collection as well.

    I’d suggest you read up on PS error handling in the link that jrv provided and rethink how to implement that. 

     Here’s a sample I was playing with. 

        clear-host 
        $smtp = ""        # sendmail error variable
        $gci = ""         # get-childitem error variable
        $error.Clear()
        # This script should run unelevated so that the next command generates 2 errors 
        $files = Get-ChildItem c:windowssecurity -Filter *.foo -ErrorVariable gci -ErrorAction SilentlyContinue -Recurse
        try {                                                                 
            # note, erroraction stop is needed to invoke catch  
            Send-MailMessage -Subject Test -from foo@bar.com -To sna@foo.com -Body test -ErrorVariable smtp -ErrorAction stop -SmtpServer smtp.foobar.com
        } 
        catch {
            "I caught an error: {0}" -f $error[0]
            "At this point in processing I have detected {0} errors." -f $error.count
            $error.RemoveAt(0)                       # ignore that error by removing it from the collection
            'Most recent error was ignored.'
        }
        ''
        '---- Error Report ----'
        "Error count is {0}" -f $error.count  
        foreach ($e in $error) {
            "Error: {0}" -f $e.tostring()
        }
        ''
        "SMTP Error count: {0}" -f $smtp.count
        foreach ($e in $smtp) {
            "SMTP Error: {0}" -f $e.tostring()
        }    
        ''
        "GCI Error count: {0}" -f $gci.count
        foreach ($e in $gci) {
            "GCI Error: {0}" -f $e.tostring()
        }
        ''
        'Finally, here is error(0)'
        $error[0]
    
    

    Produces….

    I caught an error: Unable to connect to the remote server
    At this point in processing I have detected 3 errors.
    Most recent error was ignored.
    
    ---- Error Report ----
    Error count is 2
    Error: Access to the path 'C:windowssecuritycap' is denied.
    Error: Access to the path 'C:windowssecurityaudit' is denied.
    
    SMTP Error count: 1
    SMTP Error: System.Management.Automation.ActionPreferenceStopException: The running command stopped because the preference variable "ErrorActionPreference"
     or common parameter is set to Stop: Unable to connect to the remote server
       at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
       at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
       at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
       at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
    
    GCI Error count: 2
    GCI Error: Access to the path 'C:windowssecurityaudit' is denied.
    GCI Error: Access to the path 'C:windowssecuritycap' is denied.
    
    Finally, here is error(0)
    Get-ChildItem : Access to the path 'C:windowssecuritycap' is denied.
    At line:6 char:14
    + ...    $files = Get-ChildItem c:windowssecurity -Filter *.foo -ErrorVar ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (C:windowssecuritycap:String) [Get-ChildItem], UnauthorizedAccessException
        + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
     
    
    

    • Marked as answer by

      Wednesday, November 13, 2019 8:50 PM

Понравилась статья? Поделить с друзьями:
  • Powerpoint разрывает слова как исправить
  • Powerpoint произошла серьезная ошибка во время последнего запуска
  • Powerpoint ошибка при открытии файла
  • Powerpoint ошибка при запуске приложения 0xc0000142
  • Powerpoint как изменить язык интерфейса