Powershell игнорировать ошибки

Powershell ErrorAction это ключ, с помощью которого мы можем обходить часть ошибок. Это помогает остановить скрипт, если будет ошибка. 

У меня есть две директории, одна которая существует, а другая нет. Если я выполню поиск файлов, то скрипт выведет ошибку:

$path = 'C:NotExist','C:Exist'
$path | Get-ChildItem

Get-ChildItem : Cannot find path ‘C:NotExist’ because it does not exist.

Что бы этого избежать у нас есть ключ ErrorAction со следующими значениями:

  • Continue или 0 — значение по умолчанию. Ошибка выводится на экран, но работа скрипта продолжается.
  • SilentlyContinue или 1 — ошибка не выводится на экран и скрипт продолжает работу.
  • Stop или 2 — останавливает выполнение при ошибке.
  • Ignore или 3 — игнорирует ошибки и при этом никакие логи об ошибке не сохраняются.
  • Inquire — с этим ключом у нас будет запрос на дальнейшее действия.
  • Suspend — работает при режиме Workflow (рабочих процессов). К обычным командлетам не имеет отношения.

Пример со значением по умолчанию:

$services = "NotExist","NetLogon"
$services | Get-Service -ErrorAction Continue

Powershell ErrorAction

В случае с SilentContinue у нас ошибок не будет:

Get-Process -Name "NotExist","svchost" -ErrorAction SilentlyContinue

Powershell SilentlyContinue

При этом, конечно, ключ мы должны указывать везде где ожидаем увидеть ошибку:

Powershell ошибка

Если мы выполним такую команду, то все равно получим ошибку, которая остановит процесс:

Get-Variable -Name $null -ErrorAction SilentlyContinue

Это ошибка, которая прерывает процесс и для нее нужно использовать другие методы в виде try и catch.

Теги:

#powershell

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

В 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.

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

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.

This cmdlet handles the action if an error occurs

by Srishti Sisodia

Srishti Sisodia is an electronics engineer and writer with a passion for technology. She has extensive experience exploring the latest technological advancements and sharing her insights through informative… read more


Updated on February 3, 2023

Reviewed by
Alex Serban

Alex Serban

After moving away from the corporate work-style, Alex has found rewards in a lifestyle of constant analysis, team coordination and pestering his colleagues. Holding an MCSA Windows Server… read more

  • PowerShell ErrorAction is a common parameter that comes into action whenever an error occurs.
  • This guide will discuss PowerShell ErrorAction, its parameters, and how to use them.

PowerShell ErrorAction

XINSTALL BY CLICKING THE DOWNLOAD FILE

To fix various PC problems, we recommend Restoro PC Repair Tool:
This software will repair common computer errors, protect you from file loss, malware, hardware failure and optimize your PC for maximum performance. Fix PC issues and remove viruses now in 3 easy steps:

  1. Download Restoro PC Repair Tool that comes with Patented Technologies (patent available here).
  2. Click Start Scan to find Windows issues that could be causing PC problems.
  3. Click Repair All to fix issues affecting your computer’s security and performance
  • Restoro has been downloaded by 0 readers this month.

When a command fails to execute, PowerShell displays an error based on the value set in ErrorActionPreference.

However, the ErrorAction parameter on PowerShell allows you to specify how to handle terminating errors if a command fails. The options available to handle a command’s execution are Continue, Ignore, Stop, Inquire, SilentlyContinue, and Suspend(works for PowerShell workflow only).

In this guide, we will discuss how to use PowerShell ErrorAction with its variables using examples. Let’s start!

How can I use PowerShell ErrorAction? 

1. Continue 

It is the ErrorAction parameter’s default preference. This action informs the host about the error, and the script continues to execute. You can look at this example to understand better:

  1. Press the Windows key, type PowerShell, and click Run as administrator. Windows PowerShell
  2. Copy and paste the following command and hit Enter to execute: Get-ChildItem C:nonexistentfolder -ErrorAction Continue
    Write-Output "This line will be executed even if an error occurred."
    Continue PowerShell

2. Ignore

This option doesn’t inform the host about the error and continues the execution of the script. Look at the example to understand:

  1. Open PowerShell using the same method used above.
  2. Type the following command and press Enter: Get-ChildItem C:nonexistentfolder -ErrorAction Ignore
    Write-Output "This line will be executed even if an error occurred."
    Ignore
Read more about this topic

  • Best Way to Restart Audio Driver in Windows 10
  • Runtime Error 13: Type Mismatch [Fix]
  • 2 Best Ways to Split Screen on Windows 10

3. Stop

If the error has occurred, this action stops the execution of the script. To understand better, check this example:

  1. Open PowerShell with admin rights.
  2. Type the following command and press Enter: Get-ChildItem C:nonexistentfolder -ErrorAction Stop
    Write-Output "This line will not be executed because an error occurred."
    Stop command

4. Inquire

With this option, when the error occurs, the user gets choices and prompts to determine the appropriate action. Let’s take a look at the example:

  1. First, launch PowerShell with admin rights.
  2. Copy and paste the following command, and press Enter: Get-ChildItem C:nonexistentfolder -ErrorAction Inquire
    Write-Output "This line will be executed only if you confirm the error message."
    Inquire -powershell erroraction

5. SilentlyContinue

Like the Ignore command, it will not report the error to the host and will continue the execution. However, unlike Ignore, it will add the error to the $Error variable. To understand the action better, let’s take a look at an example:

  1. Open PowerShell with administrator privileges.
  2. Type the following command and press Enter: Get-ChildItem C:nonexistentfolder -ErrorAction SilentlyContinue
    Write-Output "This line will be executed even if an error occurred."
    Sliently continue -powershell erroraction

So, this is how you can use PowerShell ErrorAction to specify what to do if the command fails to execute. If you have any questions or concerns about the parameter, feel free to let us know in the comments below. We will be happy to help!

Still having issues? Fix them with this tool:

SPONSORED

If the advices above haven’t solved your issue, your PC may experience deeper Windows problems. We recommend downloading this PC Repair tool (rated Great on TrustPilot.com) to easily address them. After installation, simply click the Start Scan button and then press on Repair All.

newsletter icon

I am trying to see if a process is running on multiple servers and then format it into a table.

get-process -ComputerName server1,server2,server3 -name explorer | Select-Object processname,machinename

Thats the easy part — When the process does not exist or if the server is unavailable, powershell outputs a big ugly error, messes up the the table and doesn’t continue. Example

Get-Process : Couldn't connect to remote machine.At line:1 char:12 + get-process <<<<  -ComputerName server1,server2,server3 -name explorer | format-table processname,machinename
+ CategoryInfo          : NotSpecified: (:) [Get-Process], InvalidOperatio   nException    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.Power   Shell.Commands.GetProcessCommand

How do I get around this? If the I would still like to get notified if the process isn’t available or Running.

If you are having prior software development experience, for exception handling we generally use PowerShell Try-Catch-Finally block. PowerShell also support try-catch-finally block to handle or respond to terminating errors in PowerShell script.

In PowerShell 2.0, common parameters related to error handling available are: -ErrorAction and -ErrorVariable

In this blog post, I will explain you about using –ErrorAction and –ErrorVariable parameter in PowerShell with examples.

The PowerShell ErrorAction parameter allows you to specify how to respond or handle terminating errors or actions to take if command fails.

ErrorAction parameter has below options available to handle execution of command if error raised

  • Continue
  • Ignore
  • Inquire
  • SilentlyContinue
  • Stop
  • Suspend

Let’s understand each of ErrorAction PowerShell options with examples

-ErrorAction Continue

ErrorAction PowerShell parameter, it basically override the $ErrorActionPreference in Windows PowerShell.

$ErrorActionPreference variable responds to which action to take in case of error raised.

using PowerShell ErrorAction parameter, it default uses continue preference. It means that in the event of error raised, its output will be written to host and script will be able to continue.

Lets consider an example to stop process RabbitMQ and handle any error produced using ErrorAction PowerShell parameter

PS C:> Stop-Process -Name RabbitMQ -ErrorAction Continue; Write-Host "Execute second command"; 

In the above example, Stop-Process cmdlet takes RabbitMQ process name and try to stop it. As it cannot find a process with given name, it throws exception.

Error raised is output to host and using –ErrorAction continue option, it continue with execution for second command.

It converts terminating errors to non-terminating errors to continue with execution and write output to host as given below

PowerShell -ErrorAction Parameter - Continue
PowerShell -ErrorAction Parameter – Continue

Do you know: How to use cat command in windows!

PowerShell -ErrorAction Ignore

PowerShell ErrorAction Ignore option does not produce any error message and write any error output on host and continue with execution.

Using -ErrorAction Ignore option no errors will be updated in PowerShell $Error variable (automatic variable).

Lets consider same example to stop RabbitMQ process. We will use -ErrorAction Ignore option to ignore any error message and continue with execution of second command.

PS C:> Stop-Process -Name RabbitMQ -ErrorAction Ignore; Write-Host "Execute second command"; 

Output of above command is as below

PowerShell -ErrorAction Parameter - Ignore
PowerShell -ErrorAction Parameter – Ignore

PowerShell Tip: How to add newline to string or variable?

-ErrorAction Inquire

PowerShell ErrorAction Inquire option produce an error and prompt user to confirm actions to take

a. Yes b. Yes to All c. Halt Command d. Suspend

Based on users action, it decide to continue with execution or halt or suspend it.

Let’s consider above example to stop RabbitMQ process using Stop-Process. We will use -ErrorAction Inquire option to let user to confirm action in the case of error produced

PS C:>> Stop-Process -Name RabbitMQ -ErrorAction Inquire; Write-Host "Execute second command";   

Output of the above command with user selection as Yes

PowerShell -ErrorAction Parameter - Inquire
PowerShell -ErrorAction Parameter – Inquire

If the user select Halt Command, it will write error message on Host and halt further execution. If the user select Suspend option, it will suspend the current execution.

Cool Tip: Replace text in string using PowerShell!

PowerShell -ErrorAction SilentlyContinue

ErrroAction SilentlyContinue in PowerShell silently continue with the execution of code if the part of code does not work or have non-terminating errors.

PowerShell ErrorAction SilentlyContinue option silence non-terminating errors and continue execution. Error will updated in PowerShell Error variable (automatic variable).

Let’s consider example to stop process name as RabbitMQ using Stop-Process. We will use -ErrorAction SilentlyContinue option to silence non-terminating errors and execution of second command.

PS C:>>> Stop-Process -Name RabbitMQ -ErrorAction SilentlyContinue; Write-Host "Execute second command";    

Output of the above command is as below

PowerShell -ErrorAction Parameter - SilentlyContinue
PowerShell -ErrorAction Parameter – SilentlyContinue

Cool Tip: Get-ChildItem cmdlet – Search for files in PowerShell!

-ErrorAction Stop

PowerShell ErrorAction Stop option display error message on host and stop further execution of code. It terminates the code.

Lets consider similar example given above to find process name as RabbitMQ. We will use -ErrorAction Stop option to check execution.

PS C:>>> Stop-Process -Name RabbitMQ -ErrorAction Stop; Write-Host "Execute second command"; 

The output of the above command is as below

PowerShell -ErrorAction Parameter - Stop
PowerShell -ErrorAction Parameter – Stop

-ErrorAction Suspend

PowerShell -ErrorAction Suspend option available in PowerShell workflows. If error raised in command, workflows will get suspended.

Cool Tip: Best way to use PowerShell Get-ChildItem cmdlet!

PowerShell ErrorVariable Parameter

When you run PowerShell command, in the event of error raised, error will added into PowerShell $Error automatic variable.

Using PowerShell ErrorVariable parameter, you can specify your own variable name to store error message.

PowerShell ErrorVariable will overwrite error message value to variable name. If you want to append error in variable name, use + in front of variable name. It will append error message.

Let’s consider an example to illustrate -ErrroVariable in PowerShell. We will use same example given above to stop process name as RabbitMQ. As command not able to find process, it will raise error.

Using -ErrorVariable PowerShell, we will store error message in processError variable name as given below

PS C:>>> Stop-Process -Name RabbitMQ -ErrorVariable processError;    

In the above command, it will add error message on PowerShell Error variable as well as on to processvariable variable.

If we print processError variable name, it will write error output on host as given below

PowerShell -ErrorVariable - variable
PowerShell -ErrorVariable – variable

Cool Tip: Get-FileHash cmdlet – Get MD5 checksum in PowerShell!

You can make the use of -ErrorAction and -ErrorVariable together to silent non-terminating errors and add error message in variable to take further action

Using the same example given above with -ErrorAction SilentlyContinue option and -ErrorVariable to store error message in processError variable.

PS C:>>> Stop-Process -Name RabbitMQ -ErrorAction SilentlyContinue -ErrorVariable processError;                        PS C:>>> $processError   

In the above code, SilentlyContinue option in PowerShell silent non-terminating errors and -ErrorVariable parameter add error message to processError variable as given below

powershell erroraction silentlycontinue
PowerShell -ErrorAction and -ErrorVariable

Cool Tip: Read more about PowerShell $PSScriptRoot Automatic Variable!

Conclusion

I hope you may have like above detailed article about PowerShell ErrorAction parameter and -ErrorVariable PowerShell parameter.

Using different options available with -ErrorAction, we can handle error message in code.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on ShellGeek home page.

Здравствуйте.

Совсем недавно меня спросили как можно обработать ошибку выполнения в PowerShell. Вопрос был про Errors Handling. И вопрос звучал на анлийском. Что-то я помнил, но смутно, так как плотно обработчики ошибок писать не доводилось. Поэтому пошел в сеть, нашел отличный материал по теме, и весь его протестировал. Материал богатый поэтому разбиваю его на две части. Уверен что вам тоже будет полезно.

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

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

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

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

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

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

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

PS D:Courses!!!Done!PowerShellscripts> Get-Service service,spooler
Get-Service : Не удается найти службу с именем службы «service».
строка:1 знак:1
+ Get-Service service,spooler     + CategoryInfo          : ObjectNotFound: (service:String) [Get-Service], ServiceCommandException     + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
 Status   Name               DisplayName                          
——   —-               ————                          
Running  spooler            Диспетчер печати     

                

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

За поведение команды при возникновении ошибки отвечает параметр ErrorAction, который может принимать одно из пяти значений:
• Continue;
• SilentlyContinue;
• Stop;
• Ignore;
• Inquire.

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

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

PS D:Courses!!!Done!PowerShellscripts> Get-Service service,spooler -ErrorAction Continue
Get-Service : Не удается найти службу с именем службы «service».
строка:1 знак:1
+ Get-Service service,spooler -ErrorAction Continue     + CategoryInfo          : ObjectNotFound: (service:String) [Get-Service], ServiceCommandException     + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

Status   Name               DisplayName                          
——   —-               ————                          
Running  spooler            Диспетчер печати                     

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

PS D:Courses!!!Done!PowerShellscripts> Get-Service service,spooler -ErrorAction SilentlyContinue
Status   Name               DisplayName                          
——   —-               ————                          
Running  spooler            Диспетчер печати                     

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

PS D:Courses!!!Done!PowerShellscripts> Get-Service service,spooler -ErrorAction Stop
Get-Service : Не удается найти службу с именем службы «service».
строка:1 знак:1
+ Get-Service service,spooler -ErrorAction Stop     + CategoryInfo          : ObjectNotFound: (service:String) [Get-Service], ServiceCommandException     + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

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

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

PS D:Courses!!!Done!PowerShellscripts> Get-Service service,spooler -ErrorAction Inquire
Подтверждение
Не удается найти службу с именем службы «service».
[Y] Да — Y  [A] Да для всех — A  [H] Прервать команду — H  [S] Приостановить — S  [?] Справка
(значением по умолчанию является «Y»):s
PS D:Courses!!!Done!PowerShellscripts>> Get-Service service,spooler -ErrorAction Inquire
Подтверждение
Не удается найти службу с именем службы «service».
[Y] Да — Y  [A] Да для всех — A  [H] Прервать команду — H  [S] Приостановить — S  [?] Справка
(значением по умолчанию является «Y»):y
Get-Service : Не удается найти службу с именем службы «service».
строка:1 знак:1
+ Get-Service service,spooler -ErrorAction Inquire     + CategoryInfo          : ObjectNotFound: (service:String) [Get-Service], ServiceCommandException     + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
Status   Name               DisplayName                          
——   —-               ————                          
Running  spooler            Диспетчер печати                     

Примечание. У параметра 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 нужное значение.

 PS D:Courses!!!Done!PowerShellscripts>> $ErrorActionPreference
Continue

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

 PS D:Courses!!!Done!PowerShellscripts>> $Error[0]
Не удается преобразовать значение «SilentContinue» в тип «System.Management.Automation.ActionPreference». Ошибка: «Не удается сопоставить пустое имя идентификатора SilentContinue с допустимым именем перечислителя.  Укажите одно из следующих имен перечислителя и попробуйте еще раз: SilentlyContinue, Stop, Continue, Inquire, Ignore»
строка:1 знак:1
+ $ErrorActionPreference = «SilentContinue»

    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

PS D:Courses!!!Done!PowerShellscripts>> $Error.Count
8
PS D:Courses!!!Done!PowerShellscripts>> $Error.Clear()
PS D:Courses!!!Done!PowerShellscripts>> $Error.Count
0

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

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

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

PS D:Courses!!!Done!PowerShellscripts>> Get-Service service,spooler -ErrorAction SilentlyContinue -ErrorVariable var
Status   Name               DisplayName                          
——   —-               ————                          
Running  spooler            Диспетчер печати                     
PS D:Courses!!!Done!PowerShellscripts>> $var
Get-Service : Не удается найти службу с именем службы «service».
строка:1 знак:1
+ Get-Service service,spooler -ErrorAction SilentlyContinue -ErrorVariable var
CategoryInfo          : ObjectNotFound: (service:String) [Get-Service], ServiceCommandException
    + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

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

В следующей части речь пойдет про обработку прерывающих ошибок (exceptions).

In normal circumstances, because we want PowerShell to work even though sometimes we have errors.
That is the reason why PowerShell errors in general are what we call non-terminating errors.

Clear-Host

$items = @()

# Generate more items
$items += for ($i = 0; $i -le 3; $i++) {
    "$($env:TEMP)$(Get-Process -Id $pid)-$($i).txt"
}

# Let's generate some errors
$items | ForEach-Object {
    Get-Item -Path $_
}

Result:

Get-Item : Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (powershell)-0.txt' because it does not exist.
At line:2 char:5
+     Get-Item -Path $_
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:UsersSander...wershell)-0.txt:String) [Get-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand

Get-Item : Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (powershell)-1.txt' because it does not exist.
At line:2 char:5
+     Get-Item -Path $_
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:UsersSander...wershell)-1.txt:String) [Get-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand

Get-Item : Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (powershell)-2.txt' because it does not exist.
At line:2 char:5
+     Get-Item -Path $_
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:UsersSander...wershell)-2.txt:String) [Get-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand

Get-Item : Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (powershell)-3.txt' because it does not exist.
At line:2 char:5
+     Get-Item -Path $_
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:UsersSander...wershell)-3.txt:String) [Get-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand

Although we got a lot of errors, PowerShell still executes the script

Error Actions

There are six error actions in PowerShell

  • Stop
  • Continue
  • SilentlyContinue
  • Ignore
  • Inquire
  • Suspend (Only used for Windows PowerShell Workflow. Cannot be used with advanced functions)

Stop

Let’s run the same script as before but now with an error action called Stop.

Clear-Host

$items = @()

# Generate more items
$items += for ($i = 0; $i -le 3; $i++) {
    "$($env:TEMP)$(Get-Process -Id $pid)-$($i).txt"
}

# Let's generate some errors
$items | ForEach-Object {
    Get-Item -Path $_ -ErrorAction Stop
}

Result:

Get-Item : Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (powershell)-0.txt' because it does not exist.
At line:2 char:5
+     Get-Item -Path $_ -ErrorAction Stop
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:UsersSander...wershell)-0.txt:String) [Get-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand

Although in the previous example we could loop through the items, this time because we set an error action, the loop stops at the first error.

Continue

This is the default error action. The error will still be displayed but the script will continue.

Clear-Host

$items = @()

# Generate more items
$items += for ($i = 0; $i -le 3; $i++) {
    "$($env:TEMP)$(Get-Process -Id $pid)-$($i).txt"
}

# Let's generate some errors
$items | ForEach-Object {
    Get-Item -Path $_ -ErrorAction Continue
}

Result:

Get-Item:
Line |
   2 |      Get-Item -Path $_ -ErrorAction Continue
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (pwsh)-0.txt' because it does not exist.
Get-Item:
Line |
   2 |      Get-Item -Path $_ -ErrorAction Continue
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (pwsh)-1.txt' because it does not exist.
Get-Item:
Line |
   2 |      Get-Item -Path $_ -ErrorAction Continue
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (pwsh)-2.txt' because it does not exist.
Get-Item:
Line |
   2 |      Get-Item -Path $_ -ErrorAction Continue
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (pwsh)-3.txt' because it does not exist.

SilentlyContinue

With SilentlyCOntinue the error message will not be displayed and the script executes the pipeline commands.

Clear-Host

$items = @()

# Generate more items
$items += for ($i = 0; $i -le 3; $i++) {
    "$($env:TEMP)$(Get-Process -Id $pid)-$($i).txt"
}

# Let's generate some errors
$items | ForEach-Object {
    Get-Item -Path $_ -ErrorAction SilentlyContinue
}

$error[0]

No error should be displayed, but the error is still saved in the $Error variable.

Result:

Get-Item:
Line |
   2 |      Get-Item -Path $_ -ErrorAction SilentlyContinue
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (pwsh)-3.txt' because it does not exist.

Ignore

The Ignore action is the same as the Silentlycontinue except the error output is not stored into $Error variable.

Clear-Host

$items = @()

# Generate more items
$items += for ($i = 0; $i -le 3; $i++) {
    "$($env:TEMP)$(Get-Process -Id $pid)-$($i).txt"
}

# Let's generate some errors
$items | ForEach-Object {
    Get-Item -Path $_ -ErrorAction Ignore
}

$error[0]

The result should be that the script returns nothing at all.

Inquire

With Inquire PowerShell helps when an error occurred due to cmdlet. It will give the option to the user with choices and prompt for appropriate action.

Clear-Host

$items = @()

# Generate more items
$items += for ($i = 0; $i -le 3; $i++) {
    "$($env:TEMP)$(Get-Process -Id $pid)-$($i).txt"
}

# Let's generate some errors
$items | ForEach-Object {
    Get-Item -Path $_ -ErrorAction Inquire
}

Result:

Confirm
Cannot find path 'C:UsersSanderAppDataLocalTempSystem.Diagnostics.Process (pwsh)-0.txt' because it does not exist.
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

Понравилась статья? Поделить с друзьями:
  • Powershell если ошибка то
  • Powershell выдает ошибку
  • Powershell copy item обработка ошибок
  • Powershell categoryinfo ошибка безопасности pssecurityexception
  • Powerpoint связанный файл недоступен ошибка диаграмма