Set-StrictMode Caveats

JavaScript guys have their "use strict" command and PowerShell monkeys are not left in the bushes.

Set-StrictMode is great and I use it all the time, mostly to detect undeclared variables at runtime. It's the type of police you want on the streets to prevent you from shooting yourself in the foot.

set-strict-mode

You can see its syntax and examples in usual Powershell way:

# This will get you the gist
Get-Help Set-StrictMode

# Some juicy examples
Get-Help Set-StrictMode -Examples
There are a few situations when this may not work as you expected.

The first case is when you use it with PowerShell remoting:

Set-StrictMode -Version Latest

Invoke-Command -ComputerName localhost -ScriptBlock {
    # Undeclared variable goes undetected since remote machine has
    # its own execution context and uses default StrictMode setting
    Write-Output "Hello $undeclaredVariable"
}

To fix this, each script block passed to remote machine must have its own Set-ScriptMode:

Invoke-Command -ComputerName localhost -ScriptBlock {
    # In this case undeclared variable will be detected properly
    Set-StrictMode -Version Latest
    Write-Output "Hello $undeclaredVariable"
}

The second case is when you declare DSC resources:

Set-StrictMode -Version Latest

Configuration MyConfiguration
{
    Node localhost
    {
        Log MyLog
        {
            Message = "Hello"
        }
    }
}

# This will result in unfriendly error
MyConfiguration -OutputPath .

The code above will produce this strange error message:

PSDesiredStateConfiguration\Node : The property 'CommandType' cannot be found on this object. Verify that the property exists.

I've once spent the entire train commute trying to fix it. After an hour of investigation I've realised that Set-StrictMode and DSC do not play along.

To fix it you need to either remove Set-StrictMode line, or disable strict mode explicitly:

# This will prevent the DSC (WMF 4.0) error from happening (hopefully this will get fixed in WMF 5.0)
Set-StrictMode -Off

2020 Update: Seems like the new version of DSC is now working properly with Set-StrictMode enabled.