PowerShell/Errors
This lesson introduces PowerShell debugging, error handling, and parameter validation.
Objectives and Skills
editAfter 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
editMultimedia
editExamples
editTry Catch
editUse 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
editfunction Get-Square()
{
Param
(
[double]$value
)
return $value * $value
}
Mandatory Validation
editThe Mandatory argument indicates that the parameter is required.[2]
function Get-Square()
{
Param
(
[parameter(Mandatory=$true)]
[double]$value
)
return $value * $value
}
Range Validation
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editError 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- 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
edit- 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- 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
editNormally 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
edit- Flashcards: Quizlet: Windows PowerShell - Errors
- Quiz: Quizlet: Windows PowerShell - Errors
See Also
editReferences
edit- ↑ Microsoft TechNet: about_Try_Catch_Finally
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Parameter validation
- ↑ Wikipedia: Data validation
- ↑ Wikipedia: Data validation
- ↑ Wikipedia: Data validation
- ↑ Microsoft TechNet: about_Functions_Advanced_Parameters
- ↑ Wikipedia: Assertion (software development)
- ↑ Wikipedia: Debugger
- ↑ Wikipedia: Divide and conquer algorithm
- ↑ Wikipedia: Integration testing
- ↑ Wikipedia: Logfile
- ↑ Wikipedia: Mission critical
- ↑ Wikipedia: Core dump
- ↑ Wikipedia: Patch (computing)
- ↑ Wikipedia: Debugging
- ↑ Wikipedia: Profiling (computer programming)
- ↑ Wikipedia: Tracing (software)
- ↑ Wikipedia: Unit testing
- ↑ Wikipedia: Verification and validation (software)