← Back to Index

PowerShell Reference

0. Basics

0.1 Hello World

# Write-Host outputs to the console host
Write-Host "Hello, World!"
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

PowerShell Core (pwsh) is an interpreted shell and scripting language.

# Execute a script file
pwsh -File script.ps1

# Execute a command string
pwsh -Command "Write-Host 'Hello'"
TERMINAL OUTPUT
Hello

0.3 Comments

# Single-line comment

<#
  Multi-line
  comment block
#>
TERMINAL OUTPUT
(No output)

0.4 Imports (Modules)

# Import a module by name or path
Import-Module Microsoft.PowerShell.Archive

# Check if a module is loaded
Get-Module Microsoft.PowerShell.Archive
TERMINAL OUTPUT
ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Manifest   1.2.5                 Microsoft.PowerShell.Archive        {Compress-Archive, Expand-Archive}

0.5 Exit Codes

# exit stops execution and returns a status code
exit 1
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

try {
    # Attempt operation that might fail
    1 / 0
} catch [DivideByZeroException] {
    Write-Host "Caught specific error: $_"
} catch {
    Write-Host "Caught general error: $_"
} finally {
    Write-Host "Cleanup phase"
}
TERMINAL OUTPUT
Caught specific error: Attempted to divide by zero.
Cleanup phase

1. Environment & Time

1.1 Variable Declaration

Variables are prefixed with $. No explicit type is required (dynamic typing).

$name = "PowerShell" # String
$version = 7         # Integer
$isCore = $true      # Boolean
TERMINAL OUTPUT
(No output)

1.2 Integer Types

PowerShell uses .NET types. Integers are [int] (32-bit) by default.

$maxInt = [int]::MaxValue # 2147483647
$bigInt = [long]::MaxValue # 9223372036854775807
TERMINAL OUTPUT
(No output)

1.3 Casting

Explicitly convert values using type accelerators in brackets.

$val = [int]"42"      # String to int
$str = [string]123    # Int to string
$arr = [int[]](1,2,3) # List to typed array
TERMINAL OUTPUT
(No output)

1.4 Truthiness

In PowerShell, $null, 0, "", $false, and empty arrays are evaluated as $false.

if ("") { "True" } else { "False" }
if (@()) { "True" } else { "False" }
TERMINAL OUTPUT
False
False

1.5 Environment Variables

Accessed via the env: drive.

# Read environment variable
$path = $env:PATH

# Set environment variable for current process
$env:MY_VAR = "secret"
TERMINAL OUTPUT
(No output)

1.6 Time

Using Get-Date or .NET DateTime.

# Current date/time
$now = Get-Date
Write-Host ($now.ToString("yyyy-MM-dd HH:mm:ss"))

# Performance measurement
$elapsed = Measure-Command { Start-Sleep -Milliseconds 10 }
Write-Host $elapsed.TotalMilliseconds
TERMINAL OUTPUT
2024-05-16 12:00:00 (example)
10.5 (example)

2. Operators & Regex

2.1 Arithmetic & Logic

Operators are prefixed with - for comparison and logic.

$sum = 10 + 3      # Addition (13)
$mod = 10 % 3      # Modulo (1)
$and = $true -and $false # Logical AND (False)
$eq  = 5 -eq 5     # Equality (True)
$ne  = 5 -ne 1     # Inequality (True)
TERMINAL OUTPUT
(No output)

2.2 Regex (-match, -replace)

Built-in operators for regular expressions.

$text = "The price is $100"
# -match sets the $Matches automatic variable
if ($text -match '\$(\d+)') {
    Write-Host $Matches[1]
}

# -replace for substitution
$newText = "Hello World" -replace "World", "PowerShell"
TERMINAL OUTPUT
100

3. Argument Parsing

3.1 CLI Argument Parsing

Use the param block at the top of a script or function.

param (
    [Parameter(Mandatory=$true)]
    [string]$InputPath,

    [int]$Count = 1, # Default value

    [switch]$Verbose # Boolean flag
)

Write-Host "Path: $InputPath, Count: $Count, Verbose: $Verbose"
TERMINAL OUTPUT
Path: ./data.txt, Count: 1, Verbose: False (example)

4. Functions & Memory

4.1 Declaration & Returns

function Get-Sum {
    param($a, $b = 0)
    # Output is automatically returned
    $a + $b
}

$result = Get-Sum -a 5 -b 10
TERMINAL OUTPUT
(No output)

4.2 References & Pointers

Use the [ref] type accelerator to pass variables by reference.

function Increment ([ref]$val) {
    $val.Value += 1
}

$counter = 10
Increment ([ref]$counter)
Write-Host $counter
TERMINAL OUTPUT
11

5. Loops & Iteration

5.1 Basic Loops

Standard C-style loops and PowerShell specific foreach.

# For loop
for ($i = 0; $i -lt 3; $i++) { Write-Host "for: $i" }

# While loop
$x = 0
while ($x -lt 3) { Write-Host "while: $x"; $x++ }
TERMINAL OUTPUT
for: 0
for: 1
for: 2
while: 0
while: 1
while: 2

5.2 Break & Continue

foreach ($n in 1..10) {
    if ($n -lt 3) { continue }
    if ($n -eq 6) { break }
    Write-Host $n
}
TERMINAL OUTPUT
3
4
5

5.3 Iterating Collections

foreach statement vs ForEach-Object cmdlet (pipeline).

$items = @(10, 20, 30)

# Statement (Faster for smaller collections)
foreach ($item in $items) { Write-Host $item }

# Pipeline (Memory efficient for large streams)
$items | ForEach-Object { Write-Host $_ }
TERMINAL OUTPUT
10
20
30
10
20
30

6. Strings & Files

6.1 Manipulation

$s = "  hello  "
$s = $s.Trim().ToUpper() # "HELLO"
$split = "a,b,c" -split "," # Array ("a", "b", "c")
$joined = @("a", "b") -join "-" # "a-b"
TERMINAL OUTPUT
(No output)

6.2 Path Joining

# Cross-platform path joining
$path = Join-Path "usr" "bin" "pwsh"
Write-Host $path
TERMINAL OUTPUT
usr/bin/pwsh (example on Linux/macOS)

6.3 Streaming I/O

Use Get-Content with -ReadCount for chunked processing.

# Read file in chunks of 1000 lines
Get-Content "large.log" -ReadCount 1000 | ForEach-Object {
    # $_ is an array of 1000 lines
    Write-Host "Processing chunk of size: $($_.Length)"
}
TERMINAL OUTPUT
Processing chunk of size: 1000 (example)

6.4 Read to Memory

# Read entire file as a single string
$content = Get-Content "file.txt" -Raw

# Read all bytes (binary)
$bytes = [System.IO.File]::ReadAllBytes("data.bin")
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation & Packing

Use [BitConverter] and byte arrays.

# Allocate 4 bytes
$buffer = New-Object byte[] 4

# Pack int32 into bytes (Little-Endian by default on most systems)
$bytes = [BitConverter]::GetBytes([int]42)
[Array]::Copy($bytes, $buffer, 4)
TERMINAL OUTPUT
(No output)

7.2 Bitwise Operations

$res = 0b1010 -band 0b1100 # AND (0b1000 -> 8)
$res = 0b1010 -bor  0b1100 # OR  (0b1110 -> 14)
$res = 0b1010 -bxor 0b1100 # XOR (0b0110 -> 6)
$res = -bnot 0b1010        # NOT
$res = 1 -shl 2            # Shift Left (4)
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

# Int to Hex string
$hex = "0x{0:x}" -f 255 # "0xff"

# Hex string to Int
$val = [Convert]::ToInt32("ff", 16) # 255
TERMINAL OUTPUT
(No output)

8. Collections & JSON

8.1 Lists, Maps & Sets

# Array (Fixed size, but + creates new)
$arr = @(1, 2); $arr += 3 

# Hashtable (Map)
$map = @{ "key" = "value" }; $map["new"] = 123

# HashSet (.NET generic)
$set = New-Object 'System.Collections.Generic.HashSet[int]'
$set.Add(1) | Out-Null
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

# JSON String to Object
$obj = '{"id": 42, "name": "pwsh"}' | ConvertFrom-Json
Write-Host $obj.name

# Object to JSON String
$json = $obj | ConvertTo-Json -Compress
TERMINAL OUTPUT
pwsh

9. Systems & Networking

9.1 TCP

Using .NET TcpClient.

$client = New-Object System.Net.Sockets.TcpClient
try {
    $client.Connect("127.0.0.1", 80)
    $stream = $client.GetStream()
    Write-Host "Connected"
} finally {
    $client.Close()
}
TERMINAL OUTPUT
Connected (if successful)

9.2 UDP

Using .NET UdpClient.

$udp = New-Object System.Net.Sockets.UdpClient
$data = [System.Text.Encoding]::UTF8.GetBytes("ping")
$udp.Send($data, $data.Length, "127.0.0.1", 8080) | Out-Null
$udp.Close()
TERMINAL OUTPUT
(No output)

9.3 Concurrency

Using ForEach-Object -Parallel (PowerShell 7+).

1..3 | ForEach-Object -Parallel {
    Write-Host "Task $_ on thread $($IsPS5 ? 'n/a' : [System.Threading.Thread]::CurrentThread.ManagedThreadId)"
    Start-Sleep -Seconds 1
}
TERMINAL OUTPUT
Task 1 on thread 15
Task 2 on thread 16
Task 3 on thread 17

9.4 SQLite

Using Microsoft.Data.Sqlite (standard in .NET).

# Load the assembly (may require installation via dotnet tool or nuget)
Add-Type -Path "Microsoft.Data.Sqlite.dll" -ErrorAction SilentlyContinue

$conn = New-Object Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:")
$conn.Open()
$cmd = $conn.CreateCommand()
$cmd.CommandText = "SELECT 42"
$result = $cmd.ExecuteScalar()
Write-Host "Result: $result"
$conn.Close()
TERMINAL OUTPUT
Result: 42