New-Variable

Create a new variable.

Syntax
      New-Variable [-Name] String [[-value] Object]
           [-scope string] [-description string] 
              [-option {None | ReadOnly | Constant | Private | AllScope}]
[-force] [-passThru] [-whatIf] [-confirm] [CommonParameters] Key -Name The name of the new variable(s). -value Object The value to assign to the variable, may be piped. -scope string The scope in which this variable is valid. Valid values are "Global", "Local", "Private" or "Script", or a number relative to the current scope ( 0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more, type "get-help about_scope". -description string A description of the variable -option ScopedItemOptions Where the new variable should be visible/changeable: ReadOnly, Constant, Private or AllScope. -force Override restrictions as long as security is not compromised. Make a best attempt at setting the variable. -passThru Pass the object through the pipeline. By default, New-Variable does not pass any objects through the pipeline. -whatIf Describe what would happen if you executed the command without actually executing the command. -confirm Prompt for confirmation before executing the command. CommonParameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutVariable.

A 'private' variable will be visible only to the current function, by default variables are visible to the current script, or if typed on the command line, to the current session/scope.

A 'read-only' variable can still be changed (or removed) by specifying -force.

A 'constant' variable cannot be changed or removed, it is constant for the duration of the session.

Examples

Create a new variable:

PS C:\>new-variable week_day
set-variable week_day monday
"$week_day"


Create a new variable and assign a value:

PS C:\>new-variable zipcode -value 90210
"$zipcode"
# Now change the value
$zipcode=54398
"$zipcode"

"Everything is on the move, nothing is constant" - Heraclitus

Related:

clear-variable - Remove the value from a variable
get-variable - Get a powershell variable
remove-variable - Remove a variable and its value
set-variable - Set a variable and a value
Equivalent bash command: export - Set an environment variable.



Back to the Top

Simon Sheppard
SS64.com