PowerShell/Errors

From Wikiversity
Jump to navigation Jump to search

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

Objectives and Skills[edit | edit source]

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[edit | edit source]

  1. Wikipedia: Debugging
  2. Wikipedia: Error handling
  3. Wikipedia: Parameter validation
  4. Wikipedia: Data validation
  5. MSDN: An Introduction to Error Handling in PowerShell
  6. WindowsITPro: Error Trapping and Handling in PowerShell
  7. Microsoft TechNet: Simplify your PowerShell Script with Parameter Validation

Multimedia[edit | edit source]

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

Examples[edit | edit source]

Try Catch[edit | edit source]

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

try
{
    $value = Read-Host 'Enter a value'
    $result = 1 / $value
    Write-Output "1 / $value = $result"

}
catch
{
    Write-Output "An error occurred dividing 1 by $value!"
}

Data Type Validation[edit | edit source]

function Get-Square()
{
    Param
    (
        [double]$value
    )
    return $value * $value   
}

Mandatory Validation[edit | edit source]

The Mandatory argument indicates that the parameter is required.[2]

function Get-Square()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [double]$value
    )
    return $value * $value   
}

Range Validation[edit | edit source]

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

function Get-Square()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateRange(1,10)]
        [double]$value
    )
    return $value * $value   
}

Not Null or Empty Validation[edit | edit source]

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

function Get-Posessive()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$value
    )
    if($value.Substring($value.Length - 1, 1) -eq 's')
    {
        $result = $value + ''''
    }
    else
    {
        $result = $value + '''s'
    }
    return $result
}

Length Validation[edit | edit source]

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

function Check-ZipCode()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateLength(5,5)]
        [string]$value
    )
    return $value
}

Pattern Validation[edit | edit source]

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

function Check-ZipCode()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidatePattern('^\d{5}$|^\d{5}-\d{4}$')]
        [string]$value
    )
    return $value
}

Script Validation[edit | edit source]

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

function Get-Reciprocal()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateScript({$_ -ne 0})]
        [double]$value
    )
    return 1 / $value   
}

Error Handling and Parameter Validation[edit | edit source]

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.

function Get-Reciprocal()
{
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateScript({$_ -ne 0})]
        [double]$value
    )
    return 1 / $value   
}

try
{
    $value = Read-Host 'Enter a value'
    $result = Get-Reciprocal $value
    Write-Output "1 / $value = $result"
}
catch
{
    Write-Output "An error occurred dividing 1 by $value!"
}

Activities[edit | edit source]

  1. 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.
  2. 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.
  3. 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.
  4. 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[edit | edit source]

  • 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.[8]
  • 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.[9]
  • The typical debugging process:[10]
    • 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.[11]
  • 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.[12]
  • 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.[13]
  • 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.[14]
  • One mechanism to transfer control, or raise an exception, is known as a throw.[15]
  • The scope for exception handlers starts with a "try" clause.[16]
  • An exception is said to be thrown and execution is transferred to a "catch".[17]
  • 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.[18]
  • Parameter validation is the automated processing, in a module, to validate the accuracy of parameters passed to that module.[19]
  • 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:[20]
    • 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.[21]
  • Data validation failures or omissions can lead to data corruption or security vulnerabilities.[22]
  • PowerShell parameter validation options include:[23]
    • parameter(Mandatory=$true)
    • ValidateRange
    • ValidateNotNullOrEmpty
    • ValidateLength
    • ValidatePattern
    • ValidateScript

Key Terms[edit | edit source]

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.[24]
debugger
A computer program that is used to test and debug other programs.[25]
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.[26]
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.[27]
log file
A file that records events which happen while a system or application runs.[28]
mission-critical
Any factor of a system whose failure will result in the failure of business operations.[29]
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).[30]
patch
A piece of software designed to update a computer program or its supporting data, to fix or improve it.[31]
print debugging
The act of watching trace statements, or print statements, that indicate the flow of execution of a process.[32]
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.[33]
tracing
A specialized use of logging to record information about a program's execution.[34]
unit testing
A software testing method by which individual blocks of source code are tested to determine if they are fit for use.[35]
validation testing
The process of checking that a software system meets specifications and that it fulfills its intended purpose.[36]

Review Questions[edit | edit source]

Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Debugging is _____.
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.
2. Debugging includes _____, _____, _____, _____, _____, _____, _____, _____, and _____.
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.
3. The typical debugging process includes:
The typical debugging process includes:

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.

4. Exception handling is _____.
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.
5. In general, exceptions are handled (resolved) by _____.
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.
6. Alternative approaches to exception handling in software are _____.
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.
7. In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote _____.
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.
8. One mechanism to transfer control, or raise an exception, is known as _____.
One mechanism to transfer control, or raise an exception, is known as a throw.
9. The scope for exception handlers starts with _____.
The scope for exception handlers starts with a "try" clause.
10. An exception is said to be thrown and execution is transferred to _____.
An exception is said to be thrown and execution is transferred to a "catch".
11. A related _____ is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block.
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.
12. Parameter validation is _____.
Parameter validation is the automated processing, in a module, to validate the accuracy of parameters passed to that module.
13. Data validation is _____.
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.
14. Data validation examples include:
Data validation examples include:

Data type validation
Range and constraint validation
Code and cross-reference validation
Structured (advanced) validation

15. Data validation responses include _____ and _____.
Data validation responses include errors that terminate processing and warnings that inform the user but allow processing to continue.
16. Data validation failures or omissions can lead to _____.
Data validation failures or omissions can lead to data corruption or security vulnerabilities.
17. PowerShell parameter validation options include:
PowerShell parameter validation options include:

parameter(Mandatory=$true)
ValidateRange
ValidateNotNullOrEmpty
ValidateLength
ValidatePattern
ValidateScript

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]

Type classification: this is a lesson resource.
Completion status: this resource is considered to be complete.