Scripting Tips and Tricks: Strict Mode

Dealing with the PoSh progeny, it is important to possess a Strict Mode to compliment the now famous Naughty Step*. Such techniques maintain discipline and keep the troops in line.

My Strict Mode is as far removed from the Wackford Squeers' school of discipline as one can imagine, being nothing more than a raised voice, but, by Jove, it works wonders! 

PowerShell also has a Strict Mode (non-shouty) to maintain order amongst the ranks. And, so, when developing and testing a script, I always make use of the following script parameter:

Set-StrictMode -version Latest

 

As a minimum this ensures that uninitialised variables (excluding uninitialised variables in strings) generate a terminating error, but the latest version of PowerShell (v4) also performs the following checks:

  • Prohibits references to uninitialised variables (including uninitialised variables in strings)
  • Prohibits references to non-existent properties of an object
  • Prohibits function calls that use the syntax for calling methods
  • Prohibits a variable without a name (${})

 

Why's that of use? Here's an example that identifies an unintialised variable...

Imagine you create a variable called $Typo and set it to 'Fingers'.

$Typo = 'Fingers'

 

You then write a conditional statement to evaluate $Typo, but don't bother to use tab-completion to re-write the variable name as it's only a short one:

If ($Tyop -eq 'Fingers') {

Write-Host $Typo

}

 

With Strict Mode set the following error will be generated when you run the above code.

 

 

You examine the variable that cannot be retrieved and notice that you have a typographical error, i.e. you've typed $Tyop and not $Typo.

Having PowerShell notify you of deviations from coding best practice saves a lot of time and effort tracking down issues in longer scripts. Furthermore, having -Latest ensures that your script will always make use of any new best practices introduced in later versions of PowerShell. Bring on v5 RTM!

*NB - sadly, PowerShell does not have Naughty Step functionality!