Did you know that PowerShell has so called strict mode in which it can catch and report any use of uninitialized variables? I’ve started doing this while scripting and it made debugging scripts so much easier! Lot’s of typos and copy/paste issues simply get detected right away.
In PowerShell v1 you can turn this mode on by executing: Set-PSDebug –strict
In PowerShell v2 by doing: Set-StrictMode –version 1 or Set-StrictMode –version 2.
(See this great article explaining all the difference.)
To make this apply to all my debugging sessions, but not to command line and PowerGUI admin console, I did the following:
1. Opened my PowerShell profile:

2. Added this code in there:
if ($host.Name -eq 'PowerGUIScriptEditorHost') { Set-StrictMode -Version 2.0 }
That’s it. Close the profile and restart the PowerGUI Script Editor.
P.S. Please forgive me the “if” workaround in common profile. In the future we will at some point start supporting a separate profile specifically for the script editor. This is the best practice and we’ll get there.
Subscribe by email




0 Responses to “Catch variable typos”