<<< Back to Search

Scripting ::: Force Variable Declaration

These commands ensure all variables are declared before its first use. This practice can save lot of time when debugging code. Force all variables to be declared

Core Snippet

# Scripting ::: Force Variable Declaration -_-
# PowerShellExamples.com

# Variables ::: Force all variables to be declared
# www.PowerShellExamples.com

# Force declaration -_-
Set-StrictMode -Version Latest

# Your script code here between Set-StrictMode Commands
# ...

# Remove declaration enforcement 
Set-StrictMode -Off
    

Practical Sample

# Sample : Variables ::: Force all variables to be declared
# Scripting ::: Force Variable Declaration -_-
# PowerShellExamples.com

# Force declaration -_-
#     Not forget at the end remove Strict Mode!
Set-StrictMode -Version Latest

# Correct Variable Management
# Variable declared (assigned)
$MyVariable = "InitialValue"

Write-Host "Using variable correctly declared - MyVariable = $MyVariable `r`n`r`n"

# When not declaring error is reported
Write-Host "Error reported when use a non declared variable:`r`n"
$x = $MyVariableNotDeclared 

# Remove declaration enforcement 
Set-StrictMode -Off
 


Result

Using variable correctly declared - MyVariable = InitialValue 


Error reported when use a non declared variable:

The variable '$MyVariableNotDeclared' cannot be retrieved because it has not been set.
At line:32 char:6
+ $x = $MyVariableNotDeclared
+      ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (MyVariableNotDeclared:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined