views:

113

answers:

2

I would like to declare some integer constants in Powershell.

Is there any good way to do that?

+1  A: 

Use -option Constant with the Set-Variable cmdlet:

Set-Variable myvar -option Constant -value 100

Now $myvar has a constant value of 100 and cannot be modified.

Paolo Tedesco
Wow, that's clunky. You have to use Set-Variable to do it, huh?
Tom
Yes, there's not unclunky way to do it :)
Paolo Tedesco
you can also modify and existing variable with either set-variable (aliased to sv) or by using get-variable (gv) and tinkering with its Options property.
x0n
+8  A: 

Use

Set-Variable test -option Constant -value 100

or

Set-Variable test -option ReadOnly -value 100

The difference between "Constant" and "ReadOnly" is that a read-only variable can be removed (and then re-created) via

Remove-Variable test -Force

whereas a constant variable can't be removed (even with -Force).

See this TechNet article for more details.

Motti Strom