# PowerShell/Errors

This lesson introduces PowerShell debugging, error handling, and parameter validation.

## Objectives and Skills

After completing this lesson, you will be able to:
* Describe basic PowerShell debugging concepts.
* Explain PowerShell error handling.
* Understand PowerShell parameter validation.
* Create PowerShell scripts that use Try Catch Finally.
* Create PowerShell functions that perform parameter validation.

## Readings

* Wikipedia: Debugging
* Wikipedia: Error handling
* Wikipedia: Parameter validation
* Wikipedia: Data validation
* MSDN: An Introduction to Error Handling in PowerShell
* WindowsITPro: Error Trapping and Handling in PowerShell
* Microsoft TechNet: Simplify your PowerShell Script with Parameter Validation

## Multimedia

* YouTube: Handle Powershell Errors With Try Catch
* YouTube: Windows PowerShell Error handling with Try...Catch
* YouTube: Introduction to Advanced Function Parameters in PowerShell
* YouTube: PowerShell - How To - Defining Parameters

## Examples
#### Try Catch

Use Try, Catch, and Finally blocks to respond to or handle terminating errors in scripts.

#### Mandatory Validation

The Mandatory argument indicates that the parameter is required.

#### Range Validation

The ValidateRange attribute specifies a numeric range for each parameter or variable value.

#### Not Null or Empty Validation

The ValidateNotNullOrEmpty attribute specifies that the parameter value cannot be null ($null) and cannot be an empty string ("").

#### Length Validation

The ValidateLength attribute specifies the minimum and maximum number of characters in a parameter or variable value.

#### Pattern Validation

The ValidatePattern attribute specifies a regular expression that is compared to the parameter or variable value.

#### Script Validation

The ValidateScript attribute specifies a script that is used to validate a parameter or variable value.

#### Error Handling and Parameter Validation

Error handling and parameter validation may be combined, but the error handling of parameter validation must occur in the calling code rather than within the function.

## Activities

* Review MCP Mag:Validation Voodoo with PowerShell Scripts. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and use functions to convert years to months, years to days, years to hours, and years to seconds. Display their approximate age in the selected timeframe. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.
* Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Use functions to convert Fahrenheit to Celsius and Celsius to Fahrenheit. Calculate and display the converted temperature. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.
* Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Use separate functions to calculate the area of each shape and then calculate and display the area of the selected shape. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.
* Review MathsIsFun: Greatest Common Factor. Create a script that asks the user to enter two integer values. Based on the recursive algorithm provided in Wikipedia: Recursion (computer science), use a recursive function to calculate the greatest common factor (greatest common divisor) of the two values and then display the result. Add parameter validation to the functions and exception handling to the script to handle any errors that could occur during the calculations.

## Lesson Summary

* Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware.
* Debugging includes interactive debugging, control flow, integration testing, log files, monitoring, memory dumps, profiling, Statistical Process Control, and special design tactics to improve detection while simplifying changes.
* The typical debugging process:
** Normally the first step in debugging is to attempt to reproduce the problem.
** After the bug is reproduced, the input of the program may need to be simplified to make it easier to debug.
** After the test case is sufficiently simplified, a programmer can use a debugger tool to examine program states (values of variables, plus the call stack) and track down the origin of the problem(s).
** Alternatively, tracing can be used. In simple cases, tracing is just a few print statements, which output the values of variables at certain points of program execution.
* Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.
* In general, exceptions are handled (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler. If exceptions are continuable, the handler may later resume the execution at the original location using the saved information.
* Alternative approaches to exception handling in software are error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values or some auxiliary global variable.
* In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.
* One mechanism to transfer control, or raise an exception, is known as a throw.
* The scope for exception handlers starts with a "try" clause.
* An exception is said to be thrown and execution is transferred to a "catch".
* A related "finally" clause is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block.
* Parameter validation is the automated processing, in a module, to validate the accuracy of parameters passed to that module.
* Data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines that check for correctness, meaningfulness, and security of data that are input to the system.
* Data validation examples include:
** Data type validation
** Range and constraint validation
** Code and cross-reference validation
** Structured (advanced) validation
* Data validation responses include errors that terminate processing and warnings that inform the user but allow processing to continue.
* Data validation failures or omissions can lead to data corruption or security vulnerabilities.
* PowerShell parameter validation options include:
** parameter(Mandatory=$true)
** ValidateRange
** ValidateNotNullOrEmpty
** ValidateLength
** ValidatePattern
** ValidateScript

## Key Terms
### assertion

    A true–false statement placed in a program to indicate that the developer thinks that the statement is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort.

### debugger

    A computer program that is used to test and debug other programs.

### divide and conquer algorithm

    An approach of recursively breaking down a problem into two or more sub-problems of the same (or related) type, until these become simple enough to be solved directly.

### integration testing

    The phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing.

### log file

    A file that records events which happen while a system or application runs.

### mission-critical

    Any factor of a system whose failure will result in the failure of business operations.

### memory dump

    The recorded state of the working memory of a computer program at a specific time, generally when the program has terminated abnormally (crashed).

### patch

    A piece of software designed to update a computer program or its supporting data, to fix or improve it.

### print debugging

    The act of watching trace statements, or print statements, that indicate the flow of execution of a process.

### profiling

    A form of dynamic program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency and duration of function calls.

### tracing

    A specialized use of logging to record information about a program's execution.

### unit testing

    A software testing method by which individual blocks of source code are tested to determine if they are fit for use.

### validation testing

    The process of checking that a software system meets specifications and that it fulfills its intended purpose.

## Review Questions

Normally the first step in debugging is to attempt to reproduce the problem. After the bug is reproduced, the input of the program may need to be simplified to make it easier to debug. After the test case is sufficiently simplified, a programmer can use a debugger tool to examine program states (values of variables, plus the call stack) and track down the origin of the problem(s). Alternatively, tracing can be used. In simple cases, tracing is just a few print statements, which output the values of variables at certain points of program execution.
Data type validation Range and constraint validation Code and cross-reference validation Structured (advanced) validation
parameter(Mandatory=$true) ValidateRange ValidateNotNullOrEmpty ValidateLength ValidatePattern ValidateScript

## Assessments

* Flashcards: Quizlet: Windows PowerShell - Errors
* Quiz: Quizlet: Windows PowerShell - Errors