Topic: Less Used Variable Properties Continued II
Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.
Last week we discussed the option of making our variables read-only. This means that without the -Force parameter, read-only variables cannot be overwritten, cleared, or deleted. This level of protection for our variable’s values is good, but it might not be the best option in some cases. Today we’ll focus on the constant option for the Options property. Let’s first create a new variable, verify it’s a constant, and then try to change its value.
New-Variable -Name String6 -Value "Here’s a new Monday variable." -Option Constant (Get-Variable -Name String6).Options Constant Set-Variable -Name String6 -Value 'Can we change it?' Set-Variable : Cannot overwrite variable String6 because it is read-only or constant.
As mentioned, with a read-only variable, we used the -Force parameter to overwrite, clear, and delete, and it worked. Let’s try that with our constant variable.
Set-Variable -Name String6 -Value ‘Can we change it?' -Force Set-Variable : Cannot overwrite variable String6 because it is read-only or constant.
Even with the -Force parameter we can’t change the variable’s value. Let’s attempt to clear it (remove its value), with the -Force parameter.
Clear-Variable -Name String6 -Force Clear-Variable : Cannot overwrite variable String6 because it is read-only or constant.
No luck. In both cases we get the same error. Let’s try to remove the variable in its entirety.
Remove-Variable -Name String6 -Force Remove-Variable : Cannot remove variable String6 because it is constant or read-only. If the variable is read-only, try the operation again specifying the Force option.
Still no luck, although we did get a mildly different message. If you create a variable that’s a constant, you can’t get rid of it, or modify it, until you end the PowerShell session; however, if it’s read-only, you’ll have some protection, and still be able to modify things, if necessary. Keep these options in mind, as you may find yourself wanting to add some protection, to your otherwise do-anything-you-want-to-them-at-any-time variables.
Bonus: Last week we saw that we were able to create a variable and then make it read-only. When we create a constant variable, the option has to be applied when the variable is first created. If you create a variable and then try to make it constant, you’ll receive the below error.
Set-Variable : Existing variable String7 cannot be made constant. Variables can be made constant only at creation time.