Set-StrictMode and Set-PSDebug -strict
In addition to PowerShell not requiring a script to specify the type of a variable, it also doesn't require any kind of declaration prior to using the variable. If the first use of a variable is to assign a value to it, this relaxed attitude doesn't cause any harm. On the other hand, reading a variable that hasn't been written to is generally not what is intended.
There are two ways to ensure that reading from an uninitialized variable will cause an error. The first, introduced in PowerShell Version 1.0, was to use the –strict
switch on the Set-PSDebug
cmdlet. Once this has been issued in a PowerShell session, references to uninitialized variables (except in string substitution) will produce an error. References inside strings will resolve to $null
. This is a global switch in the engine and is reversed by issuing Set-PSDebug
with the –off
switch. The following screenshot explains this:
The second method, introduced in PowerShell Version 2.0, is to use...