Set-StrictMode and legacy code issues

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
   # call your legacy code
    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

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s