Using Constants

by Mar 25, 2015

All PowerShell versions

Variables in PowerShell are volatile. You can overwrite and delete them – unless you create constants.

Constants can only be created when there is no such variable yet. This line creates a constant named “cannotChange” with a value of 1.

New-Variable -Name cannotChange -Value 1 -Option Constant

There is no way for you to get rid of this variable anymore for as long as PowerShell runs. The variable is tied to the current PowerShell session. Constants can be used for sensible information that you do not ever want to change.

You could define constants in your primary profile path, for example:

PS> $profile.AllUsersAllHosts

If this file exists, PowerShell executes it first whenever any PowerShell starts. If you define constants here – like your company name, important server lists, etc. – this information will be available in all PowerShell hosts and can never be overridden.

Twitter This Tip! ReTweet this Tip!