Skip to content

PPadgett/PowerShellAssertion

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

47 Commits
 
 
 
 
 
 
 
 

Repository files navigation

PowerShellAssertion

Assertions Function in PowerShell, rooted to Debug Preference

Assert-Condition PowerShell Function

This repository contains a PowerShell function Assert-Condition that allows you to insert assertion checks into your scripts.

Function Description

The Assert-Condition function checks whether a provided boolean condition is true or false. If the condition is false and the $DebugPreference is set to 'Continue' or 'Inquire', it throws an error message.

function Assert-Condition { 
    param(
        [Parameter(Mandatory = $true)]
        [bool]
        $Condition,  # Boolean condition to be checked

        [Parameter(Mandatory = $true)]
        [string]
        $Message  # Error message to display if condition is not met
    )

    if ($DebugPreference.GetHashCode() -ne 0) {
        $Condition ? $null : throw "Assertion failed: $Message"
    }
}

Usage

Assert-Condition -Condition ($variable -eq $null) -Message "Variable cannot be null"

This example will check if $variable is null. If it is, it will throw an error message "Variable cannot be null".

Why Use Assertions?

It's recommended to use assertions, aiming for an average of at least two per script. Utilizing assertions can help identify and halt errors early in the development process, thereby mitigating the cost associated with bug fixing.

DebugPreference

The DebugPreference is a shell variable that determines how Windows PowerShell responds to debug statements generated by a script or a cmdlet. Settings:

  • 'SilentlyContinue' - No effect
  • 'Stop' - Debug statements are displayed and the script Stops.
  • 'Continue' - Debug statements are displayed and the script continues to run
  • 'Inquire' - Debug statements are displayed and you are prompted to continue

Dependencies

The Assert-Condition function uses a ternary operator and thus requires PowerShell 7.0 or later, as the ternary operator is not supported in earlier versions of PowerShell.

Required Software

  • PowerShell: The script is tested on PowerShell 7.0 and above. Please make sure you have a compatible version installed. You can check your PowerShell version by running $PSVersionTable.PSVersion in a PowerShell terminal.

Installation

There's no additional software or module installation required to use the Assert-Condition function. Simply include it in your PowerShell script and use it as per your requirement.

About

Assertions Function in PowerShell, rooted to Debug Preference

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published