Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Windows Server 2012 Automation with PowerShell Cookbook

You're reading from   Windows Server 2012 Automation with PowerShell Cookbook If you work on a daily basis with Windows Server 2012, this book will make life easier by teaching you the skills to automate server tasks with PowerShell scripts, all delivered in recipe form for rapid implementation.

Arrow left icon
Product type Paperback
Published in Mar 2013
Publisher Packt
ISBN-13 9781849689465
Length 372 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
EDRICK GOAD EDRICK GOAD
Author Profile Icon EDRICK GOAD
EDRICK GOAD
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

Windows Server 2012 Automation with PowerShell Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Understanding PowerShell Scripting 2. Managing Windows Network Services with PowerShell FREE CHAPTER 3. Managing IIS with PowerShell 4. Managing Hyper-V with PowerShell 5. Managing Storage with PowerShell 6. Managing Network Shares with PowerShell 7. Managing Windows Updates with PowerShell 8. Managing Printers with PowerShell 9. Troubleshooting Servers with PowerShell 10. Managing Performance with PowerShell 11. Inventorying Servers with PowerShell 12. Server Backup Index

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:

  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:

  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 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" 
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image