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

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" 
主站蜘蛛池模板: 龙里县| 清镇市| 乐亭县| 南宁市| 保靖县| 连城县| 鄱阳县| 子洲县| 兴和县| 分宜县| 平湖市| 鄢陵县| 四川省| 陆良县| 宜宾市| 措美县| 博野县| 阿尔山市| 天长市| 鸡东县| 安吉县| 铁岭县| 灵武市| 武鸣县| 海阳市| 合肥市| 和田市| 新郑市| 奉节县| 海林市| 比如县| 金华市| 丘北县| 嵊泗县| 沾益县| 深泽县| 昭觉县| 讷河市| 镇康县| 浑源县| 昌邑市|