PoshCode Archive  Artifact [6c0dff557a]

Artifact 6c0dff557af9cb3df0be0bfbe647a3eb09cf45f424073bf253c409da6b3217e3:

  • File Assert.ps1 — part of check-in [a7fc54802b] at 2018-06-10 13:03:06 on branch trunk — A simple “assert” for testing (user: Joel Bennett size: 1127)

# encoding: ascii
# api: powershell
# title: Assert
# description: A simple “assert” for testing
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# x-poshcode-id: 1942
# x-archived: 2016-03-06T23:17:02
# x-published: 2011-06-29T21:18:00
#
#
function Assert {
#.Example
# set-content C:\test2\Documents\test2 "hi"
# C:\PS>assert { get-item C:\test2\Documents\test2 } "File wasn't created by Set-Content!"
#
[CmdletBinding()]
param( 
   [Parameter(Position=0,ParameterSetName="Script",Mandatory=$true)]
   [ScriptBlock]$condition
,
   [Parameter(Position=0,ParameterSetName="Bool",Mandatory=$true)]
   [bool]$success
,
   [Parameter(Position=1,Mandatory=$true)]
   [string]$message
)

   $message = "ASSERT FAILED: $message"
  
   if($PSCmdlet.ParameterSetName -eq "Script") {
      try {
         $ErrorActionPreference = "STOP"
         $success = &$condition
      } catch {
         $success = $false
         $message = "$message`nEXCEPTION THROWN: $($_.Exception.GetType().FullName)"         
      }
   }
   if(!$success) {
      throw $message
   }
}