Constant and Read-Only Variables

Constant and Read-Only Variables

Variables, are as their name imply, variable. Having constant and read-only variables may sound a little strange, however, in a majority of scripting and programming languages, they are normally called constants. In layman's terms, they are special variables that are marked to hold a constant value (set during initialization). In this tutorial, you will learn about constant and read-only variables.

Setup

If you have not already done so, click open Windows PowerShell ISE.

The Concept…

There is a difference between a constant variable and a read-only variable despite the fact that they are functionally equivalent. The two are similar in that constant and read-only variables are both initialized with a value during declaration and they maintain that value. The difference between them is that read-only variables cannot be changed but deleted, while you cannot do either with constant variables.

Step one.

You must use the Set-Variable Cmdlet in order to set a constant or read-only variable. You can then use Remove-Variable to delete a read-only variable. The following code show you how to define and use constant and read-only variables as well as how to clear read-only variables:

Pre

1

2

3

4

5

6

7

Set-Variable PIvalue 3.1415 –option

ConstantSet-Variable Author "Steve Sequis" –option ReadOnly

$radius = 3

$area = $PI * $radius * $radius

write-output "Area is: " + $area

write-output "This book is written by: " + $Author

Remove-Variable Author -force

Pre

Your output pane will appear as follows up running the script:

Step two.

We use the –option switch for the Set-Variable Cmdlet to specify if the variable being defined is constant or read only. The first parameter is the name of the variable, and the second is the value assigned to it. When using Set-Variable, you do not use the dollar sign in the variable name. They are only required when defining variables without using the Set-Variable Cmdlet.

After the constant or read-only variable is defined, you can use them as you would any other variable except you can't change its value. The last line in the example shows how to use the Remove-Variable Cmdlet to get rid of a read-only variable.

Remarks last but not least…

Constants and Read-Only Variables will be used quite frequently in PowerShell. Although it is not realistic to aim to memorize or recollect everything in this powerful system, these items should be on the short list of memorized topics. Join us next time for additional Windows PowerShell tutorials! Till then…