Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

PowerShell Documentation

Object-based shell and scripting for Windows (and Linux/macOS) automation.

PowerShell is a command-line shell and scripting language from Microsoft. Unlike Bash, which passes text between commands, PowerShell passes .NET objects — so you can sort, filter and format results by property without parsing text. It's the standard tool for automating Windows, Azure and Microsoft 365, and PowerShell 7 runs on Windows, macOS and Linux.

1. Introduction & Installation

  • Windows ships with Windows PowerShell 5.1. Install the modern, cross-platform PowerShell 7 with winget install Microsoft.PowerShell (command: pwsh).
  • macOS / Linux: brew install powershell / follow the docs for your distro.
  • Use Windows Terminal and VS Code's PowerShell extension.
$PSVersionTable.PSVersion           # which version?
Get-Help Get-Process -Examples      # built-in help (Update-Help downloads it)
.\script.ps1                        # run a script in the current folder
Write-Output "Hello, Codify!"

Output:

Hello, Codify!

⚠️ Common error: running scripts is disabled on this system — the execution policy blocks scripts. Allow your own scripts with Set-ExecutionPolicy -Scope CurrentUser RemoteSigned.

2. Basic Syntax & Cmdlets

Commands are cmdlets named Verb-Noun: Get-ChildItem, Set-Location, New-Item, Remove-Item, Copy-Item, Get-Content. Parameters start with -. Aliases exist for common ones (ls, cd, cat, cp, rm, dir).

Get-Location                               # pwd
Set-Location C:\Projects                   # cd
Get-ChildItem -Recurse -Filter *.js        # find files
New-Item -ItemType Directory -Path app\src -Force
Get-Command *service*                      # discover commands
Get-Help Copy-Item -Online

Comments: # line and <# block #>. Commands are case-insensitive.

$name = "Asha"
$age = 20
Write-Output "Hi $name, next year you'll be $($age + 1)"
Write-Output 'Single quotes: $name'

Output:

Hi Asha, next year you'll be 21
Single quotes: $name

⚠️ Common error: "Total: $a + $b" doesn't calculate — use a subexpression: "Total: $($a + $b)".

3. Variables & Data Types

Variables start with $. Values are .NET objects: [int], [double], [string], [bool], [datetime], [array], [hashtable], [pscustomobject].

$count = 10
$price = 99.5
$city = "Pune"
$active = $true
[int]$typed = "42"                         # type constraint converts the value
$list = 1, 2, 3                            # array
$user = @{ Name = "Ravi"; Age = 22 }       # hashtable

Write-Output $count.GetType().Name, $price.GetType().Name, $list.GetType().Name
Write-Output ($typed + 1)
Write-Output ([math]::Round(10 / 3, 2))
Write-Output ([int](7 / 2))
Write-Output $user.Name
Write-Output ("{0} lives in {1}" -f "Asha", $city)

Output:

Int32
Double
Object[]
43
3.33
4
Ravi
Asha lives in Pune

[int] rounds to the nearest even number on .5 (banker's rounding): [int](7/2) → 4, [int](5/2) → 2. Use [math]::Floor() to truncate.

⚠️ Common error: $null comparisons — write $null -eq $x (null on the left), because $x -eq $null behaves differently when $x is an array.

4. Operators

Category Operators
Arithmetic + - * / %
Comparison -eq -ne -gt -ge -lt -le (case-insensitive), -ceq (case-sensitive)
Matching -like (wildcards *), -match (regex), -contains, -in
Logical -and -or -not !
String -replace, -split, -join, -f (format)
Others .. range, `
Write-Output (5 -gt 3), ("Codify" -like "Cod*"), ("abc123" -match "\d+"), $Matches[0]
Write-Output (3 -in 1..5), (@(1, 2, 3) -contains 4)
Write-Output ("a,b,c" -split ","), ((1..4) -join "-"), ("hello world" -replace "world", "PS")
Write-Output ("HELLO" -eq "hello"), ("HELLO" -ceq "hello")

Output:

True
True
True
123
True
False
a
b
c
1-2-3-4
hello PS
True
False

⚠️ Common error: using > or == for comparison. > is redirection in PowerShell (it creates a file!). Use -gt and -eq.

5. Conditional Statements

$marks = 82
if ($marks -ge 90) {
    Write-Output "A"
} elseif ($marks -ge 75) {
    Write-Output "B"
} else {
    Write-Output "C"
}

$day = "Sat"
switch ($day) {
    { $_ -in "Sat", "Sun" } { Write-Output "Weekend"; break }
    "Mon"                    { Write-Output "Back to work" }
    default                  { Write-Output "Weekday" }
}

switch -Wildcard ("report.pdf") {
    "*.pdf" { Write-Output "PDF document" }
    "*.jpg" { Write-Output "Image" }
}

Output:

B
Weekend
PDF document

PowerShell 7 also has the ternary $x -gt 5 ? "big" : "small" and null-coalescing $name ?? "guest".

6. Loops

for ($i = 1; $i -le 3; $i++) { Write-Output "for $i" }

foreach ($lang in "pwsh", "bash", "zsh") { Write-Output $lang.ToUpper() }

1..4 | ForEach-Object { $_ * $_ }          # $_ = current pipeline object

$n = 1
while ($n -lt 100) { $n *= 3 }
Write-Output "n = $n"

$k = 0
do { $k++ } until ($k -ge 3)
Write-Output "k = $k"

Output:

for 1
for 2
for 3
PWSH
BASH
ZSH
1
4
9
16
n = 243
k = 3

⚠️ Common error: break inside ForEach-Object stops the whole script, not just the loop. Use a foreach statement when you need break/continue.

7. Functions

function Get-Greeting {
    param(
        [Parameter(Mandatory)] [string]$Name,
        [string]$Greeting = "Hello"
    )
    "$Greeting, $Name!"                    # output = return value
}

function Get-Total {
    param([int[]]$Numbers)
    ($Numbers | Measure-Object -Sum).Sum
}

function Test-Even([int]$n) { $n % 2 -eq 0 }

Get-Greeting -Name "Asha"
Get-Greeting "Ravi" -Greeting "Namaste"
Get-Total -Numbers 10, 20, 30
Test-Even 7

Output:

Hello, Asha!
Namaste, Ravi!
60
False

Everything a function outputs (not just return) becomes its result — pipe unwanted output to Out-Null. Add [CmdletBinding()] to get -Verbose, -WhatIf and other common parameters.

8. The Pipeline & Objects

The pipeline passes objects, so you filter and sort by properties:

$students = @(
    [pscustomobject]@{ Name = "Asha";  City = "Pune";   Marks = 91 }
    [pscustomobject]@{ Name = "Ravi";  City = "Delhi";  Marks = 78 }
    [pscustomobject]@{ Name = "Neha";  City = "Pune";   Marks = 85 }
    [pscustomobject]@{ Name = "Kabir"; City = "Mumbai"; Marks = 66 }
)

$students | Where-Object Marks -gt 80 | Sort-Object Marks -Descending | ForEach-Object { "$($_.Name): $($_.Marks)" }
$students | Group-Object City | Sort-Object Count -Descending | Select-Object -First 1 | ForEach-Object { "$($_.Name) x$($_.Count)" }
($students | Measure-Object Marks -Average -Maximum) | ForEach-Object { "avg $($_.Average) max $($_.Maximum)" }
($students | Select-Object -ExpandProperty Name) -join ", "

Output:

Asha: 91
Neha: 85
Pune x2
avg 80 max 91
Asha, Ravi, Neha, Kabir

Real-world examples (output depends on your machine):

Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Name, CPU, Id
Get-Service | Where-Object Status -eq Running | Measure-Object
Get-ChildItem C:\Logs -Recurse -File | Where-Object Length -gt 100MB | Select-Object FullName, Length

Formatting is the last step: Format-Table, Format-List, Out-GridView (Windows GUI), Export-Csv, ConvertTo-Json.

⚠️ Common error: using Format-Table in the middle of a pipeline — it turns objects into formatting data, so later commands can't use the properties. Format only at the end.

9. Files, Text & Data

Set-Content -Path notes.txt -Value "line 1", "line 2"
Add-Content -Path notes.txt -Value "line 3"
(Get-Content notes.txt).Count
Get-Content notes.txt | Select-String "2"

$data = @(
    [pscustomobject]@{ Item = "Book"; Qty = 2; Price = 450 }
    [pscustomobject]@{ Item = "Pen";  Qty = 5; Price = 20 }
)
$data | Export-Csv items.csv -NoTypeInformation
$rows = Import-Csv items.csv
($rows | ForEach-Object { [int]$_.Qty * [int]$_.Price } | Measure-Object -Sum).Sum

$json = $data | ConvertTo-Json -Compress
$json
($json | ConvertFrom-Json)[1].Item

Remove-Item notes.txt, items.csv
Test-Path notes.txt

Output:

3

line 2
1000
[{"Item":"Book","Qty":2,"Price":450},{"Item":"Pen","Qty":5,"Price":20}]
Pen
False

Invoke-RestMethod calls web APIs and returns objects directly: Invoke-RestMethod https://api.github.com/users/octocat | Select-Object name, public_repos.

10. Advanced Concepts

Error handling:

try {
    Get-Item C:\does\not\exist -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
    Write-Output "Not found: $($_.Exception.Message.Split([char]39)[1])"
} finally {
    Write-Output "done"
}
Not found: C:\does\not\exist
done

Non-terminating errors only stop a script with -ErrorAction Stop (or $ErrorActionPreference = "Stop" at the top of the script).

Classes (PowerShell 5+):

class Account {
    [string]$Owner
    hidden [double]$Balance
    Account([string]$owner) { $this.Owner = $owner; $this.Balance = 0 }
    [void] Deposit([double]$amount) {
        if ($amount -le 0) { throw "Amount must be positive" }
        $this.Balance += $amount
    }
    [string] ToString() { return "$($this.Owner): $($this.Balance)" }
}

$acc = [Account]::new("Asha")
$acc.Deposit(500)
$acc.ToString()
Asha: 500

Automation essentials

  • Modules: Install-Module Az, Import-Module, publish your own with a .psm1 file.
  • Remoting: Enter-PSSession server01, Invoke-Command -ComputerName s1, s2 -ScriptBlock { Get-Service }.
  • Jobs and parallelism: Start-Job, ForEach-Object -Parallel (PowerShell 7).
  • Scheduling: Task Scheduler (Register-ScheduledTask) or cron on Linux.
  • Safety: -WhatIf shows what would happen; -Confirm asks first.
Get-ChildItem *.log | Remove-Item -WhatIf       # preview a dangerous command

11. Examples with Output

Example 1 — Word frequency, top 3

"the cat and the hat and the bat" -split " " |
    Group-Object |
    Sort-Object @{ Expression = "Count"; Descending = $true }, Name |
    Select-Object -First 3 |
    ForEach-Object { "$($_.Name): $($_.Count)" }
the: 3
and: 2
bat: 1

Example 2 — FizzBuzz

(1..15 | ForEach-Object {
    if ($_ % 15 -eq 0) { "FizzBuzz" } elseif ($_ % 3 -eq 0) { "Fizz" } elseif ($_ % 5 -eq 0) { "Buzz" } else { $_ }
}) -join " "
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Example 3 — Bulk rename files

New-Item -ItemType Directory pics -Force | Out-Null
1..3 | ForEach-Object { New-Item "pics\IMG_$_.jpeg" -ItemType File | Out-Null }
Get-ChildItem pics\*.jpeg | Rename-Item -NewName { $_.Name -replace "IMG_(\d+)\.jpeg", 'photo-$1.jpg' }
(Get-ChildItem pics | Sort-Object Name).Name -join ", "
Remove-Item pics -Recurse
photo-1.jpg, photo-2.jpg, photo-3.jpg

12. Practice Problems

  1. List the 10 largest files in your Downloads folder with their size in MB.
  2. Write a function Get-FolderSize that returns the total size of a folder.
  3. Find all running processes using more than 500 MB of memory.
  4. Read a CSV of expenses and print the total per category.
  5. Write a script that backs up a folder to a zip with today's date (Compress-Archive).
  6. Call a public REST API with Invoke-RestMethod and export some fields to CSV.
  7. Create a scheduled task that runs your backup script every day at 9 PM.
  8. Write a class TodoList with Add, Complete and ToString methods.

13. Interview Questions

1. How is PowerShell different from Bash/cmd? It pipes structured .NET objects instead of text, has a consistent Verb-Noun command naming, and a full scripting language with types and classes.

2. What is a cmdlet? A lightweight command implemented as a .NET class (or advanced function) following Verb-Noun naming, e.g. Get-Process.

3. What is $_? The current object in the pipeline (also $PSItem).

4. Windows PowerShell 5.1 vs PowerShell 7? 5.1 is Windows-only on .NET Framework; 7 is cross-platform on modern .NET with new features (ternary, ??, -Parallel).

5. What is the execution policy? A safety setting controlling which scripts can run (Restricted, RemoteSigned, AllSigned, Unrestricted). It's not a security boundary.

6. Terminating vs non-terminating errors? Terminating errors stop execution and can be caught by try/catch; non-terminating ones just write to the error stream unless -ErrorAction Stop is used.

7. Write-Output vs Write-Host? Write-Output sends objects down the pipeline (can be captured); Write-Host writes directly to the console for display only.

8. What are -WhatIf and -Confirm? Safety parameters: -WhatIf shows what would happen without doing it; -Confirm asks before each action.

9. Hashtable vs PSCustomObject? A hashtable is a key/value dictionary; a [pscustomobject] is a proper object with properties that formats, sorts and exports nicely.

10. How do you run commands on remote machines? PowerShell Remoting (WinRM or SSH) with Enter-PSSession or Invoke-Command.

14. Cheat Sheet & References

Navigation and files

# move around and manage files
Get-Location; Set-Location C:\code; Get-ChildItem -Force
New-Item -ItemType Directory app; New-Item file.txt
Copy-Item a.txt b.txt; Move-Item b.txt old\; Remove-Item old -Recurse
Get-Content f.txt -Tail 20 -Wait; Set-Content f.txt "hi"; Add-Content f.txt "more"
Test-Path f.txt; Resolve-Path .\f.txt

Variables and strings

$x = 5; [int]$n = "42"; $arr = 1, 2, 3; $h = @{ a = 1 }
"Total: $($a + $b)"; "{0:N2}" -f 3.14159; $s.ToUpper(); $s.Split(",")
"a,b" -split ","; $arr -join ";"; $s -replace "old", "new"

Control flow

if ($a -gt 5) { } elseif ($a -eq 5) { } else { }
switch ($x) { 1 { "one" } default { "other" } }
foreach ($i in 1..5) { }; for ($i = 0; $i -lt 5; $i++) { }
while ($c) { }; do { } until ($c)

Pipeline

Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | Select-Object -First 5
Get-Service | Group-Object Status
1..10 | ForEach-Object { $_ * 2 } | Measure-Object -Sum
Get-ChildItem | Export-Csv files.csv -NoTypeInformation
Import-Csv data.csv | ConvertTo-Json

Functions and errors

function Do-Thing { param([Parameter(Mandatory)][string]$Name, [int]$Count = 1) "$Name x$Count" }
try { Risky -ErrorAction Stop } catch { $_.Exception.Message } finally { }
Invoke-RestMethod https://api.example.com/items
Get-ChildItem *.tmp | Remove-Item -WhatIf

Official documentation