Assertions Function in PowerShell, rooted to Debug Preference
This repository contains a PowerShell function Assert-Condition that allows you to insert assertion checks into your scripts.
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"
}
}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".
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.
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
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.
- 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.PSVersionin a PowerShell terminal.
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.