Making Variables Constant

by Nov 6, 2008

If you need to write more robust scripts, it makes sense to write-protect certain variables. Whenever you want a variable to set its content as unchangeable, add a write-protection flag:

$server = '10.10.10.10'
Set-Variable server -option ReadOnly

Now, if the variable content is changed by accident, PowerShell raises an error and prevents the change:

$server = '10.10.10.12'
Cannot overwrite variable server because it is read-only or constant.
At line:1 char:8
+ $server <<<< = '10.10.10.12'

You can easily remove the write-only flag and turn a constant back into a variable:

Set-Variable server -option None -force

To create true constants that cannot be changed once created, you'll need to define the variable using Set-Variable like this:

Set-Variable server -option Constant -value '10.10.10.10'

However, this works only if the variable did not exist before. To make sure it did not exist, you can remove it:

Remove-Variable server -force