Making Variables Constant

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

Posted Nov 06 2008, 08:00 AM by ps1

Comments

Aleksandar wrote re: Making Variables Constant
on 11-06-2008 9:06 AM

You can check with Test-Path cmdlet if the variable exists:

if (Test-Path variable:server) {

Remove-Variable server -force

}

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

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.