Read-Only and Strongly Typed Variables

by Mar 26, 2015

All PowerShell versions

To make PowerShell scripts more robust, you can code a lot of requirements right into your script variables.

When you do this, PowerShell monitors these requirements for you, and throws an error if someone breaks your rules.

Requirement #1 is the data type that you expect a variable to hold. Place the data type in square brackets, and place these before the variable. This turns a generic variable into a strongly typed variable.

 
PS> $profile.AllUsersAllHosts
C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1

PS> [int]$ID = 12

PS> $ID = 17

PS> $ID = '19'

PS> $ID = 'wrong'
Cannot convert type "string"...                                        
 

See how the variable $ID is turned into a specialized variable that can only store Integer data. When you assign a non-Integer value (like ‘19’), it is automatically converted to Integer. If that is not possible (like ‘wrong’), PowerShell throws an error.

The second requirement is “read-only” status. If you know that a variable should not change in a given portion of your code, mark it read-only. Anyone trying to change the variable will now again trigger a PowerShell exception:

 
PS> $a = 1

PS> $a = 100

PS> Set-Variable a -Option ReadOnly

PS> $a
100

PS> $a = 200
Cannot  overwrite variable.

PS> Set-Variable a -Option None -Force

PS> $a = 212                                         
 

Note how the write-protection can be turned on and off. To turn it off, set the variable option to “None”, and do not forget –Force.

As you see, the option “ReadOnly” is a soft protection. You control it, and you can turn it on and off. In a previous tip you learned about the option “Constant”. Constants are what their name says: constant. Unlike “ReadOnly”, constants can never be changed back to be writeable.

Twitter This Tip! ReTweet this Tip!