PowerShell 2.0: One Cmdlet at a Time 105 Set-StrictMode

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Set-StrictMode cmdlet.

What can I do with it?

Configure strict mode for the current scope. An error will be generated when the content of an expression, script or script block violates coding rules. Note: it is possible to use the Version parameter to pick which coding rules to use. The PowerShell help lists the current possible options as:

1.0

-- Prohibits references to uninitialized variables, except for uninitialized variables in strings.

2.0

-- Prohibits references to uninitialized variables (including uninitialized variables in strings).

-- Prohibits references to non-existent properties of an object.

-- Prohibits function calls that use the syntax for calling methods.

-- Prohibits a variable without a name (${}).

Latest

--Selects the latest (most strict) version available. Use this value to assure that scripts use the strictest available version, even when new versions are added to Windows PowerShell.

Example:

Examine what happens when you add the undefined $b to the undefined $a with strict mode off. Next, turn on strict mode using Version 1.0 and run the same test.

$a + $b Set-StrictMode -Version 1.0 $a + $b

Note the error message generated with strict mode on because $a has not been initialised.

Examine what happens when you define $a to be a numerical value and attempt to reference a property with strict mode off. Next, turn on strict mode using Version 2.0 and run the same test.

$a = 32 $a.Time Set-StrictMode -Version 2.0 $a.Time

Note the error message generated with strict mode on because the Time property does not exist.

How could I have done this in PowerShell 1.0?

You could have used Set-PSDebug, however Set-Strictmode applies only to the current scope or child scopes and does not impact the global scope. For more information on scopes in PowerShell look here.

1000 things 1% better!