What Are PowerShell Variables?
A variable in PowerShell is a named storage location in memory used to store a value that can change during script execution. Variables are prefixed with a $
sign.
$i = 1
$string = “Hello World!”
$date = Get-Date
Write-Host “Today is $date”
Variables can store strings, integers, command outputs, and more.
Understanding Data Types
PowerShell automatically assigns a data type to variables based on the content. To check a variable’s data type, use .GetType().Name
.
$x = 4
$string = “Hello World!”
$date = Get-Date
$x.GetType().Name # Output: Int32
$string.GetType().Name # Output: String
$date.GetType().Name # Output: DateTime
Common Data Types in PowerShell:
[string]
– Text strings.[int]
– 32-bit integers.[double]
– Floating-point numbers.[datetime]
– Date and time values.[hashtable]
– Key-value pairs.[regex]
– Regular expressions.
Variables can also be cast to a specific type:
$number = “4”
[int]$number # Converts string to integer
Automatic Variables
PowerShell includes built-in variables, dynamically managed by the system.
Get-ChildItem -Path C:\ -Directory | ForEach-Object { Write-Host $_.FullName }
Environment Variables
Environment variables store system and session information. Access them using $env:
.
Write-Host $env:PSModulePath
List all environment variables with:
dir env:
Variable Scopes
Scope determines where a variable is accessible. PowerShell supports the following scopes:
- Local: Default scope, accessible only in the current function or script.
- Script: Variables defined within a script but accessible throughout it.
- Global: Variables accessible throughout the entire session.
Operators in PowerShell
Arithmetic Operators
Comparison Operators
Evaluate values and return Boolean results:
$a -eq $b # Equal $a -ne $b # Not equal $a -lt $b # Less than $a -gt $b # Greater than
![]()
Logical Operators
Combine multiple conditions:
Tips for PowerShell Best Practices
- Use meaningful variable names to make your scripts easier to understand.
- Declare scope explicitly for variables shared across scripts or functions (
$script:
,$global:
). - Test scripts thoroughly before deploying in production environments.
PowerShell Structures: The Knowledgeable way to Scripting Fundamentals - Cloud Knowledge
[…] If / ElseIf / Else […]