Windows PowerShell capture Error

Source: Internet
Author: User

In the previous column, I showed you how to use Windows PowerShell to build a fairly advanced configuration tool. The tool I created provides multiple output-related options, thanks to the built-in functionality of the shell and the application of functions to objects.

The function I created has an undeniable weakness: it cannot properly handle any possible errors, such as connection or permission issues ). This is exactly what I want to solve in the current Windows PowerShell column. I will introduce the error handling function provided by Windows PowerShell.

Set Trap

In Windows PowerShell, the Trap keyword defines an error handler. When an exception occurs in your script, the shell checks whether Trap has been defined, which means it must appear in the script before any exception occurs. For this demonstration, I will organize a test script that will produce connectivity problems: I will use Get-WmiObject to connect to a computer name that does not exist in the network. My goal is to allow error Trap to write invalid computer names into a file, so as to provide me with a file that records invalid computer names. I will also add connections to two valid computers. I will use localhost ). SeeFigure 1.

Figure 1 add Trap

 

trap {  write-host "Error connecting to $computer" -fore red  "$computer" | out-file c:\demo\errors.txt -append   continue}$computer = "localhost"get-wmiobject win32_operatingsystem -comp $computer $computer = "server2"get-wmiobject win32_operatingsystem -comp $computer $computer = "localhost"get-wmiobject win32_operatingsystem -comp $computer

The output of this script is as follows:Figure 2As shown in. Please note that "Error connecting... "The message is not displayed. No Errors.txt file is created. That is to say, I did not execute my Trap at all. What exactly happened?

Figure 2This is not what I want to output!

Stop!

The key lies in understanding the differences between error messages and exceptions in the normal shell, which are divided into non-termination errors and termination errors. An error occurred while terminating the media transcoding queue ). Only exceptions can be captured. When an error occurs, the shell checks its built-in $ ErrorActionPreference variable to determine the operation you want to perform. This variable contains the "Continue" value by default, which indicates "Displaying error messages and continuing ". Changing this variable to "Stop" will display an error message and generate a caught exception. However, this means that any errors in your script will also be executed.

A better way is to stop the cmdlet that you think may cause problems. You can use the-ErrorAction or-EA) parameter to specify a common parameter supported by all cmdlet statements.Figure 3Displays the version of this script. It will work as expected, and the output is as follows:Figure 4.

Figure 3 Use-ErrorAction

 

trap {  write-host "Error connecting to $computer" -fore red    "$computer" | out-file c:\demo\errors.txt -append   continue}$computer = "localhost"get-wmiobject win32_operatingsystem -comp $computer -ea stop$computer = "server2"get-wmiobject win32_operatingsystem  -comp $computer -ea stop$computer = "localhost"get-wmiobject win32_operatingsystem  -comp $computer -ea stop

Figure 4When the-ErrorAction parameter is used, I get more useful results.

Use Continue at the end of the Trap to indicate that the shell continues executing the line after the code line that generates an exception. You can also use the keyword Break, which I will discuss later ). Note that the $ computer variable is defined in the script) is still valid in the Trap. This is because Trap is the sub-Scope of the script itself, that is, Trap can view all the variables in the script. I will introduce more information about it later ).

Complete all operations in scope

An especially tricky aspect of error capture in Windows PowerShell is the use of scopes. The shell itself represents a global scope, which contains all events that occur inside the shell. If you run a script, it obtains its own script scope. If you define a function, its internal scope is its own. This creates a parent/child type hierarchy.

When an exception occurs, the shell searches for traps in the current scope. This means that exceptions in a function will be searched for by traps in the function. If a Trap is found in the shell, the Trap is executed. If Trap ends with Continue, the shell continues to execute the line after the code line that causes an exception, but it is still in the same scope. The following uses a small amount of pseudo code to illustrate this point:

01  Trap {02    # Log error to a file03    Continue04  }05  Get-WmiObject Win32_Service –comp "Server2" –ea "Stop"06  Get-Process

If the exception occurs in row 5th, the Trap in row 1st will be executed. Trap ends with Continue, so it will Continue to execute the 6th rows.

Here are some examples of different scopes:

01  Trap {02    # Log error to a file03    Continue04  }05   06  Function MyFunction {07    Get-WmiObject Win32_Service –comp "Server2" –ea "Stop"08    Get-Process09  }10   11  MyFunction12  Write-Host "Testing!"

If the error occurs in row 7th, the shell searches for the Trap in the function scope. If not, the shell will exit the function scope and continue searching for traps in the parent scope. Because there is Trap, it will execute 1st rows. In this example, the code is Continue, so the code line after the exception in the same scope will Continue to be executed, that is, 12th rows, instead of 8th rows. In other words, the shell will not re-enter the function after exiting.

Now we will compare this behavior with the following example:

01  Function MyFunction {02    Trap {03      # Log error to a file04      Continue05    }06    Get-WmiObject Win32_Service –comp "Server2" –ea "Stop"07    Get-Process08  }09   10  MyFunction11  Write-Host "Testing!"

In this example, errors in row 6th will execute traps in row 2nd and remain within the scope of the function. The Continue keyword will remain in this scope and Continue to execute the 7th rows. If you put Trap in the scope where an error is expected, the advantage is that you are still in the scope and can continue execution in it. But what should I do if this method is not applicable to your situation?

This month's Cmdlet: Compare-Object

This tool is ideal for managing Configuration baselines. Compare-Object or Diff) is used to Compare two groups of objects. By default, it compares all attributes of each object and outputs all the differences by this command. Therefore, we assume that you have configured the services of a server in exactly the way you need them. You only need to run the following content to create a baseline:

Get-Service | Export-CliXML c:\baseline.xml

Almost all objects can be delivered to Export-CliXML, which converts objects to XML files. Then, you can run the same command such as Get-Service and compare the result with the saved XML. The command is as follows:

Compare-Object (Get-Service) (Import-CliXML   c:\baseline.xml) –property name

The add-property parameter forces the comparison to view only this property, not the entire object. In this example, you will get a list of all service names different from the original baseline, letting you know whether any service is added or deleted after the baseline is created.

Disconnected

I mentioned the Break keyword before.Figure 5Shows an example of how to use the Break keyword.

Figure 5 use the Break keyword

01  Trap {02    # Handle the error03    Continue04  }05   06  Function MyFunction {07    Trap {08      # Log error to a file09      If ($condition) {10        Continue11      } Else {12        Break13      }14    }15    Get-WmiObject Win32_Service –comp "Server2" –ea "Stop"16    Get-Process17  }18   19  MyFunction20  Write-Host "Testing!"

The following is a brief overview of the execution chain. First, execute row 19th, which calls the function in line 6th. Execute 15th rows and generate an exception. This exception is captured in row 7th, and the Trap must make a decision in row 9th. If $ condition is True, the Trap will continue to execute in row 16th.

However, if $ condition is False, Trap will be interrupted. This will exit the current scope and pass the original exception to the parent item. From the shell perspective, this means that 19th rows have encountered exceptions and are captured by 1st rows. The Continue keyword forces the shell to Continue executing the 20th rows.

In fact, both traps contain a little more code for error handling and recording. In this example, I just omitted this function code to make the actual process easier to view.

Why are you worried?

When do you need to capture errors? There are two situations: prediction of possible errors and the ability to record errors to a file or display more helpful error messages when you want to take actions beyond common error messages ).

I usually add error handling in complicated scripts to help handle errors that I can foresee. These errors include but are not limited to errors such as poor connection or permission issues.

It takes more time and effort to understand error capture. However, when you process more complex tasks in Windows PowerShell, it is necessary to implement error capture to help you build more comprehensive and professional tools.
 

Original article address

View more articles


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.