PowerShell Variables

A variable is a named storage location that holds a value. In PowerShell, variables store text, numbers, dates, lists, objects — almost any kind of data. Think of a variable as a labeled box: the label is the variable name, and the box holds the value.

Variable Basics

Every PowerShell variable starts with a dollar sign ($). This symbol tells PowerShell that what follows is a variable name, not a plain word.

  $variableName = value
   |              |
   Name           Value stored inside

Creating and Using Variables


# Store a name
$city = "Mumbai"

# Store a number
$temperature = 35

# Display the value
Write-Host $city
Write-Host $temperature

Output:


Mumbai
35

Variable Naming Rules

  • Variable names always start with $
  • Names are case-insensitive$Name and $name are the same variable
  • Names can contain letters, numbers, and underscores
  • Names cannot contain spaces (use underscores instead)
  • Avoid using PowerShell reserved words as names
Valid NamesInvalid Names
$firstName$first name (space not allowed)
$total_amount$total-amount (hyphen not allowed)
$server1$1server (cannot start with number after $)
$_tempData(all of these are valid)

Assigning Different Value Types


# String (text)
$product  = "Laptop"

# Integer (whole number)
$quantity = 10

# Decimal (floating point)
$price    = 49999.99

# Boolean (true or false)
$inStock  = $true

# Date
$today    = Get-Date

# Null (empty / no value)
$result   = $null

Displaying Variable Values


# Method 1 – Just type the variable name
$product

# Method 2 – Use Write-Host
Write-Host $product

# Method 3 – Embed in a string with double quotes
Write-Host "The product is $product"

# Method 4 – Use Write-Output (preferred in scripts)
Write-Output $product

Output:


Laptop
Laptop
The product is Laptop
Laptop

Updating Variable Values


$score = 50
Write-Host "Initial score: $score"

# Update the value
$score = 85
Write-Host "Updated score: $score"

# Increment the value
$score = $score + 10
Write-Host "After increment: $score"

# Shorthand increment
$score += 5
Write-Host "After shorthand: $score"

Output:


Initial score: 50
Updated score: 85
After increment: 95
After shorthand: 100

Variable Types – How PowerShell Handles Data

PowerShell automatically detects the data type of a variable based on the assigned value. This is called implicit typing. However, the type can also be set explicitly.

Check the Type of a Variable


$city = "Delhi"
$city.GetType()

$count = 100
$count.GetType()

Output:


IsPublic  IsSerial  Name    BaseType
--------  --------  ----    --------
True      True      String  System.Object

IsPublic  IsSerial  Name   BaseType
--------  --------  ----   --------
True      True      Int32  System.ValueType

Explicit Type Declaration


# Force a variable to always be a string
[string]$code = "A001"

# Force a variable to always be an integer
[int]$age = 28

# Force a variable to always be a boolean
[bool]$isActive = $true

# Force a variable to always be a decimal
[double]$salary = 75000.50

When the type is set explicitly, PowerShell will convert any assigned value to that type or throw an error if conversion is not possible.


[int]$num = "42"    # Works – "42" converts to integer 42
[int]$num = "abc"   # Error – "abc" cannot convert to integer

Special Built-In Variables

PowerShell includes several automatic variables that are always available and hold important system data.

VariableDescriptionExample Value
$PSVersionTablePowerShell version informationPSVersion: 7.4.0
$env:USERNAMECurrent logged-in user nameAdmin
$env:COMPUTERNAMEName of the computerDESKTOP-ABC123
$env:USERPROFILEPath to the user's home folderC:\Users\Admin
$PWDCurrent working directoryC:\Users\Admin
$HOMEUser's home directoryC:\Users\Admin
$trueBoolean value TrueTrue
$falseBoolean value FalseFalse
$nullEmpty value (nothing)null
$_Current object in a pipeline(varies)
$argsArguments passed to a scriptArray of values
$ErrorThe last error that occurredError object

# Use built-in variables
Write-Host "Hello, $env:USERNAME"
Write-Host "Computer: $env:COMPUTERNAME"
Write-Host "Current folder: $PWD"

Output:


Hello, Admin
Computer: DESKTOP-ABC123
Current folder: C:\Users\Admin\Documents

Variable Scope

Scope defines where a variable is accessible. PowerShell has three main scopes:

+------------------------------+
|  Script Scope                |
|  (variables in .ps1 file)    |
|  +------------------------+  |
|  |  Function Scope        |  |
|  |  (variables inside     |  |
|  |   a function)          |  |
|  +------------------------+  |
+------------------------------+
|  Global Scope                |
|  (variables in console       |
|   session, accessible        |
|   everywhere)                |
+------------------------------+

# Global variable – accessible everywhere in the session
$Global:appName = "eStudy247"

# Script variable – accessible only in the current script
$Script:version = "2.0"

# Local variable – default scope (accessible only in current block)
$localValue = "This stays here"

function Show-Info {
    Write-Host $Global:appName   # Works – global scope
    Write-Host $localValue        # May not work if declared outside
}

Remove a Variable


$tempData = "Temporary"

# Remove the variable
Remove-Variable -Name tempData

# Verify it is gone (will throw an error or return nothing)
$tempData

Multiple Assignment


# Assign the same value to multiple variables at once
$a = $b = $c = 0

Write-Host $a   # 0
Write-Host $b   # 0
Write-Host $c   # 0

Variable in String (String Interpolation)


$item  = "Keyboard"
$price = 1200

# Double quotes allow variable expansion
Write-Host "Item: $item, Price: $price"

# Single quotes treat everything as literal text
Write-Host 'Item: $item, Price: $price'

Output:


Item: Keyboard, Price: 1200
Item: $item, Price: $price

Always use double quotes when embedding variables inside strings. Single quotes do not expand variables.

Summary

Variables in PowerShell always start with $. They store any type of data — strings, numbers, booleans, dates, or even entire objects. PowerShell sets the type automatically, but explicit type declarations keep data consistent. Built-in automatic variables provide system information without needing to query anything. Understanding scope ensures that variables are accessible exactly where they are needed in scripts.

Leave a Comment