Constants in PowerShell

This topic contains 4 replies, has 3 voices, and was last updated by  Bob McCoy 3 years, 11 months ago.

  • Author
  • #10654

    Bob McCoy

    Does PowerShell treat ReadOnly variables differently? That is, is there a performance difference in declaring a New-Varibable -Option ReadOnly versus just a regular variable assignment?

  • #10657

    Don Jones

    ReadOnly variables are essentially constants. Once created, you can't change them – "Read Only." The purpose isn't performance related; it's to establish something that cannot be changed later. They exist for the same reason that constants exist alongside variables in most programming languages – mainly to provide a named version of a value (e.g., $ACCOUNT_LOCKED instead of 5 or something).

  • #10666

    Dave Wyatt

    Technically, PowerShell supports both ReadOnly variables and Contstant variables. The difference is that you can still change a Read-Only variable by passing the -Force switch to the various cmdlets. Constants, once defined, are there for the entire session. You can't change or delete them without closing PowerShell.

    PS C:\Source\temp> New-Variable -Name 'CONST' -Value 'Constant' -Option Constant
    PS C:\Source\temp> New-Variable -Name 'READONLY' -Value 'ReadOnly' -Option ReadOnly
    PS C:\Source\temp> Set-Variable -Name 'READONLY' -Value 'NewValue' -Force
    PS C:\Source\temp> Set-Variable -Name 'CONST' -Value 'NewValue' -Force
    Set-Variable : Cannot overwrite variable CONST because it is read-only or constant.
    At line:1 char:1
    + Set-Variable -Name 'CONST' -Value 'NewValue' -Force
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : WriteError: (CONST:String) [Set-Variable], SessionStateUnauthorizedAccessException
        + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand
    PS C:\Source\temp> $READONLY
    PS C:\Source\temp> $CONST
  • #10667

    Don Jones

    Kind of a hair-split. Point being, no, there's not a performance difference. And, if you think you might want to change the ReadOnly variable, don't make it ReadOnly :). They're constants for all intents and purposes; "-Option Constant" was added a bit later in the development cycle as a kind of syntax sugar and a "more read-only than read-only."

    So while there's a technical functional difference, the *intent* of the two is basically the same. One is more or less a leftover.

    Performance, no perceptible difference between either of them and a standard variable that you simply avoid making changes to.

  • #10693

    Bob McCoy


You must be logged in to reply to this topic.