← Home

PowerShell Lab

FOC
Basics & Variables

Write-Output prints to pipeline. Read-Host reads user input. # starts a comment. Variables start with $.

$name = Read-Host "Enter name"
Write-Output "Hello, $name!"        # string interpolation
$x = 42                              # int
$pi = 3.14                           # double
$flag = $true                        # boolean
$arr = @(1, 2, 3)                    # array
$ht = @{ key = "value" }             # hashtable
Control Flow
# if / elseif / else
if ($x -gt 10) {
    Write-Output "big"
} elseif ($x -gt 0) {
    Write-Output "small"
} else {
    Write-Output "zero or negative"
}

# for loop
for ($i = 0; $i -lt 5; $i++) { Write-Output $i }

# foreach
foreach ($item in $arr) { Write-Output $item }

# while
while ($x -gt 0) { $x-- }

# switch
switch ($code) {
    200 { "OK" }
    404 { "Not Found" }
    default { "Unknown" }
}
Functions & Parameters
function Greet-User {
    param([string]$Name)
    return "Hello, $Name!"
}
Greet-User -Name "Alice"   # Hello, Alice!

# Typed parameters
function Add-Numbers {
    param([int]$A, [int]$B)
    return $A + $B
}

# Splatting
$params = @{ Name = "notepad"; ErrorAction = "SilentlyContinue" }
Get-Process @params
String & Array Methods
# Strings
$s = "Hello World"
$s.ToUpper()              # HELLO WORLD
$s.ToLower()              # hello world
$s.Split(" ")             # @("Hello","World")
$s.Contains("World")     # True
$s.Replace("Hello","Hi") # Hi World
$s.Substring(0, 5)       # Hello
$s.Length                 # 11

# Arrays
$arr = @(3, 1, 2)
$arr += 4                 # @(3,1,2,4)
$arr | Sort-Object        # 1,2,3,4
$arr | Where-Object { $_ -gt 2 }    # 3,4
$arr | ForEach-Object { $_ * 2 }    # 6,2,4,8
$arr -join ","            # "3,1,2,4"
$arr.Count                # 4
Pipeline & Filtering
# Pipeline passes objects between cmdlets
Get-Process | Where-Object { $_.CPU -gt 10 }
             | Sort-Object CPU -Descending
             | Select-Object -First 5 Name, CPU

# Measure-Object
@(1,2,3) | Measure-Object -Sum -Average

# Group-Object
Get-ChildItem | Group-Object Extension

# Select with calculated properties
Get-Process | Select-Object Name,
    @{N='MemMB';E={[math]::Round($_.WS/1MB,1)}}
File System
# Navigate
Get-Location               # current directory
Set-Location "C:\Temp"     # cd

# List / Search
Get-ChildItem -Recurse -Filter "*.ps1"
Get-ChildItem | Where-Object { $_.Length -gt 1MB }

# Read / Write
Get-Content "file.txt"
Set-Content "out.txt" -Value "hello"
Add-Content "log.txt" -Value "new line"
Select-String -Path "*.log" -Pattern "error"

# File operations
New-Item -Path "test.txt" -ItemType File
Copy-Item "a.txt" "b.txt"
Remove-Item "old.txt"
Test-Path "file.txt"       # True/False
Services & Processes
# Processes
Get-Process                           # list all
Get-Process -Name "notepad"           # by name
Stop-Process -Name "notepad"          # kill
Start-Process "notepad.exe"           # launch

# Services
Get-Service                           # list all
Get-Service -Name "Spooler"           # specific
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"
Restart-Service -Name "wuauserv"

# Filter by startup type
Get-CimInstance Win32_Service |
    Where-Object StartMode -eq "Auto"
Networking
# IP info
Get-NetIPAddress -AddressFamily IPv4
ipconfig /all

# Connectivity
Test-Connection -ComputerName "8.8.8.8" -Count 2
Test-NetConnection -ComputerName "google.com" -Port 443

# TCP connections
Get-NetTCPConnection -State Listen
Get-NetTCPConnection | Where-Object LocalPort -eq 80

# Web requests
Invoke-WebRequest -Uri "https://example.com"
Invoke-RestMethod -Uri "https://api.example.com/data"
Data Formats (JSON, CSV)
# JSON
$obj = '{"name":"Alice"}' | ConvertFrom-Json
$obj.name                          # Alice
$obj | ConvertTo-Json -Depth 10    # back to JSON

# CSV
$data = Import-Csv "data.csv"
$data | Export-Csv "out.csv" -NoTypeInformation
"Name,Age`nAlice,30" | ConvertFrom-Csv

# StringData (INI-style)
$kv = "key1=val1`nkey2=val2" | ConvertFrom-StringData
$kv.key1                           # val1
Registry & Environment
# Environment variables
$env:PATH                              # read
$env:FOO = "bar"                       # set (session)
Remove-Item Env:FOO                    # remove

# Registry
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion" -Name "ProgramFilesDir"
Set-ItemProperty "HKCU:\Software\MyKey" -Name "Mode" -Value "On"
Remove-ItemProperty "HKCU:\Software\MyKey" -Name "Mode"

# Output redirection
Get-Date > date.txt                    # overwrite
Get-Date >> log.txt                    # append
Jobs & Remoting
# Background jobs
Start-Job -ScriptBlock { Get-Process }
Get-Job                               # list jobs
Receive-Job -Id 1                     # get results
Remove-Job -State Completed           # clean up

# Remoting (WinRM)
Test-WSMan -ComputerName "Server01"
Enter-PSSession -ComputerName "Server01"
Invoke-Command -ComputerName "Server01" -ScriptBlock { hostname }
Copy-Item "file.txt" -ToSession $s -Destination "C:\dest"

# Scheduled tasks
Get-ScheduledTask
Register-ScheduledTask -TaskName "Test" -Action $action -Trigger $trigger
SCORE: 0   STREAK: 0   1/20
SCORE: 0   STREAK: 0   1/20