Constant and Read-Only PowerShell Variables for Admins Who Fear Change

powershell-techtargetMost people define a variable in a programming language as a placeholder for something else. The variable is a

bucket that stuff goes into, comes out of, gets changed and gets removed. However, there’s a certain subset of PowerShell variables that can be defined but can never change. These sets are called constants and read-only variables.

Constants and read-only variables are pretty much functionally equivalent. Values are assigned to a constant or read-only variable, but can never change. In the case of an actual constant, it can’t even be removed. Let’s go over a quick example.

If you’ve written scripts in PowerShell you’ve most likely assigned variables in the form $Variable = 'some value' . This is common practice and is the typical way in which a variable is defined. But there is a built-in PowerShell cmdlet called Set-Variable  that can assign variable values as well. It’s not as commonly used because writing $Bucket = 'Full'  and Set-Variable -Name 'Bucket' -Value 'Full'  are functionally equivalent.

I created that $Bucket  variable and assigned it a value of Full. I then changed the value of $Bucket  to Empty. But what if I want to create a constant? In that case, use Set-Variable  with an additional parameter called Option . By using the Option  parameter, admins can assign the $Bucket  variable as always being ‘Full… Continue reading on SearchWindowsServer.

Adam Bertram

Chief Automator at Adam the Automator, LLC
Adam Bertram is an independent consultant, technical writer, trainer and presenter. Adam specializes in consulting and evangelizing all things IT automation mainly focused around Windows PowerShell. Adam is a Microsoft Windows PowerShell MVP, 2015 powershell.org PowerShell hero and has numerous Microsoft IT pro certifications. He authors IT pro course content for Pluralsight, is a regular contributor to numerous print and online publications and presents at various user groups and conferences.You can find Adam here on the blog or on Twitter at @adbertram.

Latest posts by Adam Bertram (see all)