More Control with Strict Mode

by Apr 12, 2022

Occasionally, PowerShell may behave unexpectedly. For example, when you enter an IPv4 address without quotes, PowerShell happily accepts this – and does nothing. Why?


In cases like this, it may pay off to activate the “Strict Mode” which emits stricter exceptions when something is wrong:

PS> Set-StrictMode -Version Latest

The property '3.4' cannot be found on this object. Verify that the property exists.
At line:1 char:1 

With Strict Mode enabled, it turns out that the input “” was interpreted by PowerShell like this: The float number 1.2 was taken, and then the property “3” and inside of it, the property “4” was queried. Of course, these properties do not exist. With Strict Mode disabled, PowerShell does not complain about non-existing properties and just returns “nothing”. That is what happened.

Enabling Strict Mode can also help to identify typos in your code. Just make sure you enable Strict Mode exclusively on your script development machine. Never add it to production code. Strict Mode is just a helping hand for script developers. Once a script is done and turned over to other users, do not leave your development tools inside of it.

The reason why Set-StrictMode should never be placed inside your code (and always be entered interactively or as part of your profile script) is simple: other PowerShell script developers may have deliberately chosen to count on loose exceptions, and when your script forces Strict Mode, it also applies to all code (and modules) used from there. Enabling Strict Mode in production may suddenly emit a plethora of red exceptions by code that runs fine.

Twitter This Tip! ReTweet this Tip!