Read-only variables in PowerShell are variables whose values cannot be modified once they are set. In PowerShell, this means that after assigning a value to a read-only variable, any attempt to change its value will result in an error.
PowerShell read-only variables are particularly useful when you want to protect important data or configurations from unintentional modification during script execution.
In PowerShell, there are several methods to implement read-only variables such as using ReadOnly and Constant options.
In this article, we will discuss how to create read-only variables.
How to Create PowerShell Read-Only Variables Using ReadOnly Option
The New-Variable
cmdlet in PowerShell allows you to create new variables. You can specify the -Option ReadOnly
parameter while creating a variable to make the variable read-only.
New-Variable -Name myHost -Value "INCORP-EU-101" -Option ReadOnly $myHost
In the above example, $myHost
variable is a read-only variable that stores the value “INCORP-EU-101“.
After executing the above command, any attempts to change the value of $myHost
value will result in an error, as given below.
$myHost = "INCORP-EU-L101"
(base) PS C:\> $myHost = "INCORP-EU-L101"
Cannot overwrite variable myHost because it is read-only or constant.
At line:1 char:1
+ $myHost = "INCORP-EU-L101"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (myHost:String) [], SessionStateUnauthorizedAccessException
+ FullyQualifiedErrorId : VariableNotWritable
How to Create PowerShell Read-Only Variables Using Constant Option
The New-Variable
cmdlet in PowerShell allows you to create new variables. You can specify the -Option Constant
parameter while creating a variable to make the variable constant to achieve the read-only behavior.
New-Variable -Name myComp -Value "INCORP-AU-101" -Option Constant $myComp
This command creates a read-only variable named $myComp
.
If you try to change the value of the above $myComp
variable, it will throw an error.
$myComp = "INCORP-AU-L101"
(base) PS C:\> $myComp = "INCORP-AU-L101"
Cannot overwrite variable myComp because it is read-only or constant.
At line:1 char:1
+ $myComp = "INCORP-AU-L101"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (myComp:String) [], SessionStateUnauthorizedAccessException
+ FullyQualifiedErrorId : VariableNotWritable
Cool Tip: How to create variables using PowerShell!
Conclusion
I hope the above article on how to create read-only variable in PowerShell using the Readonly and Constant options of New-Variable cmdlet is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.