Does PowerShell support constants?

I would like to declare some integer constants in PowerShell.

Is there any good way to do that?


Use

Set-Variable test -Option Constant -Value 100

or

Set-Variable test -Option ReadOnly -Value 100

The difference between "Constant" and "ReadOnly" is that a read-only variable can be removed (and then re-created) via

Remove-Variable test -Force

whereas a constant variable can't be removed (even with -Force).

See this TechNet article for more details.


Here is a solution for defining a constant like this:

const myConst = 42

Solution taken from http://poshcode.org/4063

    function Set-Constant {
  <#
    .SYNOPSIS
        Creates constants.
    .DESCRIPTION
        This function can help you to create constants so easy as it possible.
        It works as keyword 'const' as such as in C#.
    .EXAMPLE
        PS C:\> Set-Constant a = 10
        PS C:\> $a += 13

        There is a integer constant declaration, so the second line return
        error.
    .EXAMPLE
        PS C:\> const str = "this is a constant string"

        You also can use word 'const' for constant declaration. There is a
        string constant named '$str' in this example.
    .LINK
        Set-Variable
        About_Functions_Advanced_Parameters
  #>
  [CmdletBinding()]
  param(
    [Parameter(Mandatory=$true, Position=0)]
    [string][ValidateNotNullOrEmpty()]$Name,

    [Parameter(Mandatory=$true, Position=1)]
    [char][ValidateSet("=")]$Link,

    [Parameter(Mandatory=$true, Position=2)]
    [object][ValidateNotNullOrEmpty()]$Mean,

    [Parameter(Mandatory=$false)]
    [string]$Surround = "script"
  )

  Set-Variable -n $name -val $mean -opt Constant -s $surround
}

Set-Alias const Set-Constant

To use a specific type of value, say Int64, you can explicitly cast the value used in set-variable.

For instance:

set-variable -name test -value ([int64]100) -option Constant

To check,

$test | gm

And you'll see that it is an Int64 (rather than Int32, which would be normal for the value 100).


Use -option Constant with the Set-Variable cmdlet:

Set-Variable myvar -option Constant -value 100

Now $myvar has a constant value of 100 and cannot be modified.