Variables and Data Types
Learn how to create and use variables in PowerShell. Understand data types, type casting, arrays, hashtables, and special variables.
📖 6 min read📅 2026-02-10Core Concepts
Variables in PowerShell
Variables store data for later use. In PowerShell, all variable names start with the $ symbol.
# Creating variables
$name = "ShellRAG"
$age = 5
$isActive = $true
$pi = 3.14159
# Using variables
Write-Host "Welcome to $name!"
Write-Host "Pi is approximately $pi"Variable Naming Rules
- Must start with
$ - Can contain letters, numbers, and underscores
- Are case-insensitive (
$Nameand$nameare the same) - Use meaningful names in scripts
# Good variable names
$userName = "John"
$fileCount = 42
$isCompleted = $false
$serverList = @("server1", "server2")
# Valid but less readable
$x = 10
$_ = "current item" # Special pipeline variableData Types
PowerShell is based on .NET, so it supports all .NET data types:
Common Types
# String
$greeting = "Hello, World!"
$greeting.GetType().Name # String
# Integer
$count = 42
$count.GetType().Name # Int32
# Double (decimal)
$price = 19.99
$price.GetType().Name # Double
# Boolean
$isReady = $true
$isDone = $false
# DateTime
$now = Get-Date
$birthday = [datetime]"1990-05-15"
# Array
$colors = @("Red", "Green", "Blue")
# Hashtable
$person = @{
Name = "Alice"
Age = 30
City = "New York"
}Type Casting
Force a variable to a specific type:
# Cast to integer
[int]$number = "42"
[int]$rounded = 3.7 # Result: 4
# Cast to string
[string]$text = 123 # Result: "123"
# Cast to double
[double]$decimal = "3.14"
# Cast to boolean
[bool]$flag = 1 # Result: $true
[bool]$flag2 = 0 # Result: $false
# Cast to datetime
[datetime]$date = "2026-01-15"
# Cast to array
[array]$list = "single item"Strings
String Types
# Double-quoted: Supports variable expansion and escape sequences
$name = "World"
$greeting = "Hello, $name!" # "Hello, World!"
$newline = "Line1`nLine2" # Two lines
# Single-quoted: Literal strings (no expansion)
$literal = 'Hello, $name!' # "Hello, $name!" (literal text)
$raw = 'No `n expansion here' # No escape processing
# Here-strings: Multi-line strings
$multi = @"
This is a multi-line string.
Variable expansion works: $name
Useful for templates and scripts.
"@
$literalMulti = @'
This is a literal here-string.
No $variable expansion.
'@String Operations
$text = "PowerShell is Awesome"
# Length
$text.Length # 21
# Case conversion
$text.ToUpper() # "POWERSHELL IS AWESOME"
$text.ToLower() # "powershell is awesome"
# Substring
$text.Substring(0, 10) # "PowerShell"
# Contains / StartsWith / EndsWith
$text.Contains("Shell") # True
$text.StartsWith("Power") # True
$text.EndsWith("Awesome") # True
# Replace
$text.Replace("Awesome", "Great") # "PowerShell is Great"
# Split
$text.Split(" ") # @("PowerShell", "is", "Awesome")
# Join
$words = @("Hello", "World")
$words -join ", " # "Hello, World"
# Trim
" spaces ".Trim() # "spaces"
" spaces ".TrimStart() # "spaces "
" spaces ".TrimEnd() # " spaces"
# String formatting
$formatted = "Name: {0}, Age: {1}" -f "Alice", 30
# "Name: Alice, Age: 30"
# Padding
"42".PadLeft(6, '0') # "000042"
"Hi".PadRight(10, '.') # "Hi........"String Interpolation
$user = "Alice"
$count = 5
# Simple variable
"Hello, $user"
# Property access (use $())
$process = Get-Process -Id $PID
"Current process: $($process.Name)"
# Expressions (use $())
"Sum: $(2 + 3)"
"Files: $((Get-ChildItem).Count)"
# Array indexing
$colors = @("Red", "Green", "Blue")
"First color: $($colors[0])"Arrays
Creating Arrays
# Standard array
$fruits = @("Apple", "Banana", "Cherry")
# Implicit array (comma-separated)
$numbers = 1, 2, 3, 4, 5
# Range operator
$range = 1..10 # 1 through 10
# Empty array
$empty = @()
# Single-item array
$single = @("only one")
# Typed array
[int[]]$integers = 1, 2, 3
[string[]]$names = "Alice", "Bob"Array Operations
$colors = @("Red", "Green", "Blue", "Yellow")
# Access by index (0-based)
$colors[0] # "Red"
$colors[-1] # "Yellow" (last item)
$colors[1..2] # @("Green", "Blue")
# Count
$colors.Count # 4
$colors.Length # 4
# Add items (creates new array)
$colors += "Purple"
# Check if contains
$colors -contains "Red" # True
"Red" -in $colors # True
# Find index
[array]::IndexOf($colors, "Blue") # 2
# Filter
$colors | Where-Object { $_ -like "B*" } # "Blue"
# Iterate
foreach ($color in $colors) {
Write-Host $color
}
# ForEach method
$colors.ForEach({ $_.ToUpper() })ArrayList (Mutable)
Standard arrays are immutable (adding creates a new array). Use ArrayList for better performance:
$list = [System.Collections.ArrayList]@()
$list.Add("Apple") | Out-Null
$list.Add("Banana") | Out-Null
$list.Remove("Apple")
$list.Count # 1
# Or use Generic List
$typedList = [System.Collections.Generic.List[string]]::new()
$typedList.Add("Hello")
$typedList.Add("World")Hashtables
Hashtables are key-value pair collections (like dictionaries):
# Creating a hashtable
$person = @{
Name = "Alice"
Age = 30
City = "New York"
Skills = @("PowerShell", "Python")
}
# Access values
$person["Name"] # "Alice"
$person.Name # "Alice" (dot notation)
$person.Skills[0] # "PowerShell"
# Add/modify entries
$person["Email"] = "alice@example.com"
$person.Age = 31
# Remove entries
$person.Remove("City")
# Check if key exists
$person.ContainsKey("Name") # True
$person.ContainsValue(31) # True
# Get all keys/values
$person.Keys
$person.Values
# Iterate
foreach ($key in $person.Keys) {
Write-Host "$key : $($person[$key])"
}
# Count
$person.CountOrdered Hashtables
Regular hashtables don't preserve insertion order. Use [ordered] if order matters:
$orderedPerson = [ordered]@{
FirstName = "Alice"
LastName = "Smith"
Age = 30
}Special Variables
PowerShell has many built-in automatic variables:
# Booleans
$true
$false
$null
# Current object in pipeline
$_ # or $PSItem
# Last command result
$? # True if last command succeeded
# Last error
$Error[0] # Most recent error
# Home directory
$HOME
# Current directory
$PWD
# Process ID
$PID
# PowerShell version
$PSVersionTable
# Script information
$MyInvocation
$PSScriptRoot # Directory of current script
$PSCommandPath # Full path of current script
# Preference variables
$ErrorActionPreference # Default: "Continue"
$VerbosePreference # Default: "SilentlyContinue"
$ConfirmPreference # Default: "High"Type Checking
# Check type
$value = 42
$value -is [int] # True
$value -is [string] # False
$value -isnot [string] # True
# Get type name
$value.GetType().Name # "Int32"
$value.GetType().FullName # "System.Int32"
# Check if null
$null -eq $variable # True if $variable is nullExercises
- Create a hashtable representing a server (Name, IP, OS, RAM, Status)
- Create an array of numbers 1–20 and filter only even numbers
- Build a formatted string that shows current user, date, and OS
- Create an ordered hashtable of weekdays and their abbreviations
- Practice string operations: reverse a string, count vowels, extract a domain from an email
Next: Operators and Comparisons — learn about arithmetic, comparison, and logical operators!