I am a big fan of Set-StrictMode cmdlet.
I always add
Set-StrictMode -Version Latest
into all my PowerShell scripts, this helps a lot to catch typos and call for missing variables earlier.
However, that’s ok if you work with your own scripts only. But if you call some legacy scripts from your script, you can discover many hidden issues.
So here we will try to understand how to overcome such issues.
Hammer Approach
If we can’t or don’t want to modify legacy code we can just temporary disable strict mode.
Set-StrictMode -Off
try
{
# call your legacy code
}
finally
{
Set-StrictMode -Version Latest
}
Missing Variable
Sometimes, I see code like
if (-not $myVariable)
{
# Do something ...
}
In non-strict mode, if variable does not exist, PowerShell treats it as $null
In strict mode we get
The variable '$myVariable' cannot be retrieved because it has not been set.
At line:1 char:16
+ if ($myVariable <<<< ) {}
+ CategoryInfo : InvalidOperation: (myVariable:Token) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
Safe equivalent for check of variable existence is
if (-not (Test-Path Variable:myVariable))
{
# Do something ...
}
Equivalent for check for $Global:myVariable is
Test-Path Variable:Global:myVariable
Missing Property
Sometimes, code tries to access object’s property which does not exist.
$property = $object.MissingProperty
In non-strict mode, if property does not exist, PowerShell treats it as $null
In strict mode we get
Property 'MissingProperty' cannot be found on this object. Make sure that it exists.
At line:1 char:9
+ $object. <<<< MissingProperty
+ CategoryInfo : InvalidOperation: (.:OperatorToken) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFoundStrict
Safe equivalent would be
$property = $object | Select-Object -ExpandProperty MissingProperty -ErrorAction SilentlyContinue