PowerShell Constants and Read-Only Variables
A constant is a variable whose value can never change. A read-only variable is a variable whose value can only change with a special override.
Create a constant
Set-Variable with the Constant option creates a constant. Print it like any variable.
Set-Variable -Name city -Value "Seattle" -Option Constant
$cityCreate a read-only variable
Set-Variable with the ReadOnly option creates a read-only variable. It prints like any variable too.
Set-Variable -Name count -Value 5 -Option ReadOnly
$countForce a change to a read-only variable
A plain assignment cannot change a read-only variable. Set-Variable with Force can.
Set-Variable -Name count -Value 5 -Option ReadOnly
Set-Variable -Name count -Value 9 -Force
$countExample
Set-Variable -Name appName -Value "Shop" -Option Constant
Set-Variable -Name visits -Value 1 -Option ReadOnly
$appName
$visits
Set-Variable -Name visits -Value 2 -Force
$visitsKey points
- Constant: a variable whose value can never change after it is set.
- Read-only: a variable whose value stays fixed unless you force a change.
- Set-Variable: use Set-Variable with the Option setting to create a constant or a read-only variable.
- Force: use the Force setting to change a read-only variable.
In this example, the first line creates a constant app name. The second line creates a read-only visit count. The next two lines print both values. The last two lines force the visit count to a new value and print it.
Note
Force works on a read-only variable but never on a constant. A constant stays fixed for good.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which setting lets you change a read-only variable?