Using Assertions

by Jun 19, 2020

Often, your code needs to assert certain prerequisites. For example, you may want to ensure that a given folder exists, and use code like this:

# path to download files to
$OutPath = "$env:temp\SampleData"

# does it already exist?
$exists = Test-Path -Path $OutPath -PathType Container

# no, create it
if (!$exists)
{
  $null = New-Item -Path $OutPath -ItemType Directory
} 

Instead of coding this over and over again, you can start using a library of assertion functions. Here is one that ensures that a folder exists:

filter Assert-FolderExists
{
  $exists = Test-Path -Path $_ -PathType Container
  if (!$exists) { 
    Write-Warning "$_ did not exist. Folder created."
    $null = New-Item -Path $_ -ItemType Directory 
  }
}

With this function, your code becomes a lot cleaner. These lines assign folder paths to variables and at the same time make sure the folders exist:

# making sure a bunch of folders exist
'C:\test1', 'C:\test2' | Assert-FolderExists

# making sure the path assigned to a variable exists
($Path = 'c:\test3') | Assert-FolderExists 

Read more about this technique here: https://powershell.one/code/10.html.


Twitter This Tip! ReTweet this Tip!