Skip to content

PowerShell Variables

How to declare, assign, and manage variables in PowerShell, including dynamic typing, strong typing with type accelerators, scope modifiers, and built-in automatic variables for system operations.

A variable is a named memory location used to store data, object references, and execution results during the life of a PowerShell session or script. In PowerShell, all variable names are identified by the dollar sign ($) prefix and can hold everything from simple text and integers to complex .NET objects.

Declaring and Assigning Variables with the $variable Syntax

Unlike languages that require explicit declaration statements like dim or var, PowerShell creates a variable dynamically the moment you assign a value to it using the assignment operator (=):

Consolepowershell
$ServerName = "web-prod-01"
$MaxConnections = 150
$IsActive = $true

To display or retrieve the stored content, reference the variable name directly:

Consolepowershell
$ServerName
Outputplaintext
web-prod-01

Variable Cmdlets

While standard assignment ($var = value) is most common, PowerShell also provides a dedicated provider and cmdlet set to manage variables programmatically:

Cmdlet Purpose Example
Set-Variable Creates or overwrites a variable value Set-Variable -Name "Port" -Value 8080
Get-Variable Retrieves variable objects and metadata Get-Variable -Name "Port"
Clear-Variable Resets a variable's value to $null without deleting it Clear-Variable -Name "Port"
Remove-Variable Deletes the variable completely from memory Remove-Variable -Name "Port"

Environment Variables

Operating system environment variables are accessed directly through the env: PSDrive using the syntax $env:VARIABLE_NAME:

Consolepowershell
$env:COMPUTERNAME
$env:USERNAME
Outputplaintext
WORKSTATION-01
Tom

Strongly-Typed Variables

By default, PowerShell is dynamically typed. When you assign a value, the engine selects the underlying .NET type automatically:

Consolepowershell
$Count = 10
$Count.GetType().FullName
Outputplaintext
System.Int32

To enforce data integrity and prevent unintended type conversion, you can prefix the variable with an explicit type accelerator:

Consolepowershell
[int]$PortNumber = 8080
[string]$LogLevel = "Verbose"
[datetime]$DeploymentDate = "2026-09-22"

Once a variable is strongly typed, assigning an incompatible value throws a terminating conversion error:

Consolepowershell
[int]$MaxUsers = "Unlimited"
Outputplaintext
MetadataError: Cannot convert value "Unlimited" to type "System.Int32". Error: "The input string 'Unlimited' was not in a correct format."

For more detailed information on primitive and composite data types, see PowerShell Data Types.

Variable Scopes

Scope determines where a variable is visible and accessible in a script. By default, PowerShell variables are locally scoped to the current context (the current script, function, or prompt session).

PowerShell supports several explicit scope modifiers:

Scope Modifier Description
$local:var Explicitly references the current local execution context.
$script:var Visible anywhere within the executing .ps1 script file, including within inner functions.
$global:var Visible across the entire PowerShell engine session and all running commands.
$private:var Accessible only inside the declaring scope; cannot be inherited by child scopes.
scope-demo.ps1powershell
$script:GlobalCounter = 100

function Update-Counter {
    $local:Counter = 5
    Write-Output "Inside function local: $local:Counter"
    Write-Output "Inside function script: $script:GlobalCounter"
}

Update-Counter
Write-Output "Outside function script: $script:GlobalCounter"

where:

  • $script:GlobalCounter is accessible throughout the script file.
  • $local:Counter is isolated to the Update-Counter function and discarded upon return.
Consolepowershell
pwsh ./scope-demo.ps1
Outputplaintext
Inside function local: 5
Inside function script: 100
Outside function script: 100

For an in-depth guide on scope inheritance and variable isolation within functions, see Local Variables in Functions.

Automatic and Special Variables

PowerShell provides built-in automatic variables that store system state, pipeline context, and runtime metadata. These variables cannot be overwritten.

Core Built-in Values

  • $null: Represents an empty or unassigned reference.
  • $true / $false: Built-in literals for boolean values.
Consolepowershell
$TargetObject = $null
$TargetObject -eq $null
Outputplaintext
True

Contextual and Pipeline Variables

  • $_ (or $PSItem): Represents the current object passing through the pipeline.
  • $args: An array of undeclared parameters passed to a function or script. See For Loop Command-Line Arguments.
  • $?: Contains the execution status ($true or $false) of the immediately preceding command.
  • $LASTEXITCODE: Holds the integer exit code of the last native CLI executable run. See PowerShell Return Code.
  • $PSScriptRoot: Contains the absolute directory path of the currently executing script.

Practical Example: Tracking System Resource Limits

The following script stores typed operational thresholds, reads environment parameters, and uses automatic variables to validate disk health.

monitor-storage-threshold.ps1powershell
[string]$TargetDrive     = "C:"
[int]$AlertThresholdGB   = 50

$Drive = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='$TargetDrive'"
$FreeGB = [math]::Round($Drive.FreeSpace / 1GB, 2)

$Report = [PSCustomObject]@{
    HostName       = $env:COMPUTERNAME
    DriveEvaluated = $TargetDrive
    FreeCapacityGB = $FreeGB
    RequiresAlert  = ($FreeGB -lt $AlertThresholdGB)
    CheckedBy      = $env:USERNAME
}

$Report

where:

  • [string]$TargetDrive and [int]$AlertThresholdGB declare strongly-typed variables.
  • Get-CimInstance queries the disk configuration for the specified drive.
  • 1GB is a PowerShell numeric multiplier converting raw bytes to gigabytes.
  • $env:COMPUTERNAME and $env:USERNAME inject ambient system context.

Execute the script from the console:

Consolepowershell
pwsh ./monitor-storage-threshold.ps1
Outputplaintext
HostName       : WEB01
DriveEvaluated : C:
FreeCapacityGB : 5.57
RequiresAlert  : True
CheckedBy      : Tom
Navigation