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 (=):
$ServerName = "web-prod-01"
$MaxConnections = 150
$IsActive = $trueTo display or retrieve the stored content, reference the variable name directly:
$ServerNameweb-prod-01Variable 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:
$env:COMPUTERNAME
$env:USERNAMEWORKSTATION-01
TomStrongly-Typed Variables
By default, PowerShell is dynamically typed. When you assign a value, the engine selects the underlying .NET type automatically:
$Count = 10
$Count.GetType().FullNameSystem.Int32To enforce data integrity and prevent unintended type conversion, you can prefix the variable with an explicit type accelerator:
[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:
[int]$MaxUsers = "Unlimited"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. |
$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:GlobalCounteris accessible throughout the script file.$local:Counteris isolated to theUpdate-Counterfunction and discarded upon return.
pwsh ./scope-demo.ps1Inside function local: 5
Inside function script: 100
Outside function script: 100For 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.
$TargetObject = $null
$TargetObject -eq $nullTrueContextual 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 ($trueor$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.
[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
}
$Reportwhere:
[string]$TargetDriveand[int]$AlertThresholdGBdeclare strongly-typed variables.Get-CimInstancequeries the disk configuration for the specified drive.1GBis a PowerShell numeric multiplier converting raw bytes to gigabytes.$env:COMPUTERNAMEand$env:USERNAMEinject ambient system context.
Execute the script from the console:
pwsh ./monitor-storage-threshold.ps1HostName : WEB01
DriveEvaluated : C:
FreeCapacityGB : 5.57
RequiresAlert : True
CheckedBy : Tom