CodeToLive

PowerShell Variables & Data Types

Variables in PowerShell are used to store data that can be referenced and manipulated throughout your scripts.

Variable Basics

PowerShell variables are prefixed with $ and can contain letters, numbers, and underscores:

# Creating variables
$name = "PowerShell"
$version = 7.2
$isAwesome = $true

Data Types

PowerShell is dynamically typed but supports explicit typing:

# Common data types
[string]$text = "Hello"
[int]$number = 42
[bool]$flag = $true
[datetime]$date = Get-Date
[array]$list = 1,2,3
[hashtable]$dict = @{Key="Value"}

Special Variables

PowerShell has several automatic variables:

# Current directory
$PWD

# User's home directory
$HOME

# Last command's output
$_

# Error information
$Error

# Command line arguments
$args

# Current script's path
$MyInvocation.MyCommand.Path

Variable Scopes

Variables can have different scopes:

# Local scope (default)
$localVar = "Value"

# Script scope
$script:scriptVar = "Script Value"

# Global scope
$global:globalVar = "Global Value"

# Private scope (not visible to child scopes)
$private:privateVar = "Private Value"

Working with Variables

# Get all variables
Get-Variable

# Remove a variable
Remove-Variable -Name "varName"

# Strongly typed variables with validation
[ValidatePattern("[A-Za-z]+")][string]$name = "Valid"
[ValidateRange(1,100)][int]$age = 30
[ValidateSet("Red","Green","Blue")][string]$color = "Red"

Common Data Types

Type Description Example
[string] Text data $name = "John"
[int] Integer numbers $count = 42
[double] Floating-point numbers $price = 19.99
[bool] Boolean values $enabled = $true
[datetime] Date and time $now = Get-Date
[array] Collection of items $numbers = 1,2,3
[hashtable] Key-value pairs $person = @{Name="John"; Age=30}

Type Conversion

# Implicit conversion
$number = "123" + 456  # Results in "123456"

# Explicit conversion
[int]"123" + 456  # Results in 579

# Using cast operators
[datetime]"2023-01-01"

# Using .NET methods
[System.Convert]::ToInt32("100")

Here Strings

For multi-line strings:

$multiLine = @"
This is a 
multi-line
string
"@

Write-Host $multiLine