PowerShell: strict mode and the variable provider

When working in script languages where declaration of variables is not used there is always the problem of typos in names. PowerShell has a possibility to use 'strict" mode: when a variable is used without an initial assignment you get an error:

set-psdebug -strict -trace 0

But now I have problems with third-party scripts that check for the existance of variables by comparing them to $null like this:

if ($var -eq $null) { ... }

This throws an error in strict mode.

To solve this problem use the variable provider. The variable provider gives you access to all variables. There is also a provider for functions, the environment variables, etc. You can even write your own providers.

Check this out:

ls variable:*

ls function:*

ls env:*

To prevent the error in the variable existance check do the following:

if (!(Test-Path variable:var)) { ... }

No Comments