To bring Adam Luniewski's helpful answer and Jeroen Mostert's helpful recommendation together:
You cannot set variable options as part of a variable assignment.
- While you can apply validation attributes to an assignment, as shown in Adam's answer, they can't be used to enforce read-only behavior.
Only New-Variable
and Set-Variable
allow you to specify variable options, via their -Option
parameter.
Therefore, to get what you want:
Use New-Variable
(or Set-Variable
) with -Option Constant
, which prevents its later removal.
Note that your variable can by default still be shadowed by a variable of the same name created in a descendant scope; e.g.: Set-Variable -Option Constant var 1; & { $var = 2; $var }
- a new, local $var
was created inside the script block, which shadowed the outer, constant one.
To prevent that, use -Option Constant, AllScope
, which ensures that all code in the session sees the same value for a variable with the given name, but note that code that tries to create its own copy can then fail, so you should only do this with variable names that can be assumed not to be used for different purposes in other code.
To assign a specifically typed value, pass it to -Value
via an expression (enclosed in (...)
, the grouping operator) - if necessary:
# Create a constant, [int]-typed variable.
# Note that just `-Value 42` would be sufficient here.
New-Variable -Option Constant -Name myVar1 -Value ([int] 42)
Just -Value 42
would be sufficient in this case, because PowerShell by default parses unquoted arguments that can be parsed as numbers as such, with [int]
as the smallest type chosen; you can even use number-type suffixes such as L
for [long]
. However, negative "number strings" (e.g., -42
) are not recognized as numbers and require (...)
.
Similarly, a quoted token (e.g., '42'
) would implicitly create a [string]
, a hashtable literal (@{ key = 'value' }
) would create a hashtable, and so on; a simple variable reference (e.g., $HOME
) or member access (e.g., $HOME.ToUpper()
) would preserve the variable / member value's type.
See also:
This answer provides a comprehensive overview of how unquoted token are parsed in argument mode (the parsing mode for commands to which arguments are passed).
This answer explains how PowerShell parses number literals (which also applies when passing unquoted tokens as command arguments).