🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Strict Mode

Strict mode is a setting that makes PowerShell stop on mistakes it would usually ignore. It catches a mistyped variable or property name early, instead of silently using an empty value.

Strict mode catches an uninitialized variable

With strict mode on, reading a variable that was never set stops with an error. The try block catches it and prints the real message.

Set-StrictMode -Version Latest
try { $total + 1 } catch { "Caught: " + $_.Exception.Message }

Strict mode catches a misspelled property

A misspelled property name is also an error in strict mode. The message names the property that could not be found.

Set-StrictMode -Version Latest
$book = [PSCustomObject]@{ Title = "Dune"; Author = "Frank Herbert" }
try { $book.Titel } catch { "Caught: " + $_.Exception.Message }

Turning strict mode off restores lenient behavior

Set-StrictMode -Off turns the checks off again. Reading an unset variable then gives an empty value instead of an error.

Set-StrictMode -Version Latest
Set-StrictMode -Off
$other = $missingVar
"After Off: [$other]"

Example

Set-StrictMode -Version Latest
try { $count + 1 } catch { "Caught: " + $_.Exception.Message }
$book = [PSCustomObject]@{ Title = "Dune" }
try { $book.Titel } catch { "Caught: " + $_.Exception.Message }
Set-StrictMode -Off
$free = $missingVar
"Lenient: [$free]"

Key points

  • Strict mode: a setting that makes PowerShell stop on mistakes it would usually ignore.
  • Uninitialized variable: a variable name used before any value was assigned to it.
  • Use Set-StrictMode -Version Latest to turn strict mode on.
  • Property check: in strict mode, reading a property name that does not exist stops with an error.
  • Use Set-StrictMode -Off to turn strict mode off again.

In this example, strict mode first catches an uninitialized variable and then a misspelled property, and turning strict mode off restores the lenient empty value.

Note

strict mode set inside a script does not change the caller session after the script ends.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

In strict mode, what happens when code reads $book.Titel instead of $book.Title?