官术网_书友最值得收藏!

Dealing with errors in PowerShell

When creating a script in any language, error handling is needed to ensure proper operations. Error handling is useful when debugging scripts and ensuring scripts work properly, but they can also present alternative methods of accomplishing tasks.

How to do it...

Carry out the following steps:

  1. Create a simple function that uses no error handling
    Function Multiply-Numbers
    {
        Param($FirstNum, $SecNum)
        
        Write-Host ($FirstNum * $SecNum)
    }
  2. Test the function using various arguments:
    How to do it...
  3. Update the function using a Try/Catch block:
    Function Multiply-Numbers
    {
        Param($FirstNum, $SecNum)
        Try
        {
            Write-Host ($FirstNum * $SecNum)
        }
        Catch
        {
            Write-Host "Error in function, present two numbers to multiply"
        }
    }
  4. Test the Multiply-Numbers function using various arguments:
    How to do it...
  5. In the PowerShell console, execute a command to generate an error such as Get-Item foo.
  6. View the $Error variable to return the error code history.
    How to do it...

How it works...

In the first step, we create a function that takes two numbers, multiplies them, and returns the result. As we see in the second step, the function operates normally as long as two numbers are presented, but if something other than a number is presented, then an unfriendly error is returned.

In the third step, our updated script uses a Try/Catch block to find errors and return a more friendly error. The Try block attempts to perform the multiplication, and if an error is returned then processing exits. When the Try block fails for any reason, it then executes the Catch block instead. In this case, we are returning a command specific error message, in other scenarios we could initiate an alternative task or command that was based on the error.

The fifth and sixth steps generate an error in the PowerShell console, and then show the $Error variable. The $Error variable is an in-built array that automatically captures and stores errors as they happen. You can view the variable to report all errors listed, or you can use indexing such as $Error[1] to return specific errors.

There's more...

  • Clearing error codes: By default, the $Error array will retain a number of error codes. These errors are only removed from the array when it reaches its maximum size, or when the user session is ended. It is possible to clear out the array before doing a task, so that you can then review the $Error array after and know that all the alerts are relevant.
    $Error.Count
    $Error.Clear()
    $Error.Count

    This example starts by returning the number of items in the array. Then $Error.Clear() is called to empty the array. Lastly, the number of array items is returned to confirm that it has been cleared.

  • $ErrorActionPreference: In many programming/scripting languages, there are methods to change the default action when an error occurs. In VBScript, we had the option "On Error Resume Next", which told the script to continue on as though no error had occurred. In PowerShell, we have the $ErrorActionPreferece variable. There are four settings for this variable:
    • Stop: Whenever an error occurs, the script or process is stopped. This is the default action.
    • Continue: When an error occurs, the error will be reported and the process will continue.
    • SilentlyContinue: When an error occurs, PowerShell will attempt to suppress the error and the process will continue. Not all errors will be suppressed.
    • Inquire: When an error occurs, PowerShell will prompt the operator to take the correct action.

To set your preference, simply set the variable to the desired string value as shown in the following code:

$ErrorActionPreference = "Stop" 
主站蜘蛛池模板: 隆安县| 元谋县| 玉树县| 个旧市| 增城市| 仁布县| 土默特右旗| 社会| 荣成市| 凉城县| 盐城市| 吕梁市| 新闻| 阳朔县| 东丰县| 同心县| 遂昌县| 白银市| 名山县| 南岸区| 马鞍山市| 定州市| 孟津县| 奈曼旗| 苍梧县| 玛多县| 启东市| 巧家县| 睢宁县| 平阳县| 文水县| 定远县| 西林县| 云阳县| 金秀| 准格尔旗| 朝阳县| 肥城市| 确山县| 岳阳县| 韶山市|