Introduction to PowerShell

Introduction to PowerShell in PowerShell: Picture a vast industrial parts warehouse. Every item that arrives is received onto a pallet with a printed traveller…

The Analogy: The Catalogued Parts Warehouse

Picture a vast industrial parts warehouse. Every item that arrives is received onto a pallet with a printed traveller card riveted to it: part name, bin location, quantity, weight, supplier. Nothing sits on a shelf as an anonymous lump. When a picker asks for the 6203 bearings in bin A-14, the forklift brings the whole pallet WITH its card, so the receiving clerk can read any field off it directly. This is exactly how PowerShell treats data: every command hands back fully described objects, each carrying labelled properties, not a smear of undifferentiated text.

Contrast the older stockroom next door, run on paper chits. There a request returns a single hand-scrawled line: 6203 bearing A14 42. To read the quantity you count characters from the right and hope the clerk kept the spacing consistent. That is the Unix bash model: commands emit unstructured strings, and you slice them with cut, awk, and grep, guessing at column positions. It works until someone writes the quantity before the bin, and every downstream tool silently reads the wrong number.

The warehouse also enforces a strict naming grammar on its operations. Every action form is titled Verb-Noun: Get-Pallet, Move-Pallet, Remove-Pallet, Set-BinLabel. A new worker who has never seen Restart-Conveyor can still guess that it exists, because the vocabulary of verbs (Get, Set, New, Stop, Restart) is small and approved, and the nouns simply name the things in the building. PowerShell cmdlets follow the same Verb-Noun contract, which is why the whole command set is discoverable rather than memorised.

Now imagine the warehouse abandons the traveller cards and the naming grammar. Parts arrive as unlabelled blanks in identical grey totes, and operations get cryptic codes like op41 and zx. A picker holding a tote cannot tell a bearing from a bushing without measuring it by hand, and cannot guess which code moves a pallet versus scraps it. Every task becomes a fragile ritual of counting characters and consulting a dog-eared cheat sheet. That is what a pure-text shell degrades into at scale: the information is technically present but unaddressable, so automation shatters the moment a format shifts by a single space.


Syntax or Core Structure

PowerShell's surface is small because it is regular. Three ideas cover most of it: cmdlets are named Verb-Noun, they emit objects, and the pipe | passes those objects (not text) from one cmdlet to the next.

# 1. Every command is Verb-Noun: an approved verb plus the target noun.
Get-Process               # read the running processes
Sort-Object CPU           # reorder objects by a property
Select-Object -First 5    # keep only the first five objects

# 2. The pipe passes whole objects; each stage reads properties off what it receives.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

# 3. You address data by property NAME, never by column position.
$part = [PSCustomObject]@{ Name = 'Bearing-6203'; Bin = 'A-14'; Qty = 42 }
$part.Name                # -> Bearing-6203
$part.Qty * 2             # -> 84  (Qty is a real number, so arithmetic works)

Discovery is built in. Because every command is Verb-Noun and every result is an object, you can find and understand commands without leaving the shell.

# Find commands by wildcard on the noun:
Get-Command *Service*

# Read the manual, with runnable samples:
Get-Help Get-Process -Examples

# Inspect what an object actually contains:
Get-Process | Get-Member

The single most important habit is Get-Member. Because output is always an object, you can pipe anything into it to see the type and every property and method exposed. Discovery never requires a web search; the shell describes its own data.


Technical Depth: Objects, Members, and the Extended Type System

Everything Returns an Object

Even output that looks like plain text is an object underneath. When you assign a custom record and address its fields, PowerShell reads the actual property values, and arithmetic on a numeric property behaves like a number rather than like the digits of a string.

$part = [PSCustomObject]@{ Name = 'Bearing-6203'; Bin = 'A-14'; Qty = 42 }
'Name: ' + $part.Name
'Bin: ' + $part.Bin
'Qty: ' + $part.Qty
'Qty doubled: ' + ($part.Qty * 2)
'Type: ' + $part.GetType().Name

Output:

Name: Bearing-6203
Bin: A-14
Qty: 42
Qty doubled: 84
Type: PSCustomObject

Properties Versus Methods

Get-Member separates an object's data (properties) from its behaviour (methods). The custom part exposes its fields as NoteProperties; listing them shows exactly what is addressable by name.

$part = [PSCustomObject]@{ Name = 'Bearing-6203'; Qty = 42 }
$part |
    Get-Member -MemberType NoteProperty |
    ForEach-Object { '{0} is a {1}' -f $_.Name, $_.MemberType }

Output:

Name is a NoteProperty
Qty is a NoteProperty

The distinction is practical: a property is read with a bare dot such as .Length, while a method is invoked with parentheses such as .ToUpper(). Mixing them up is one of the most common early errors.

ConcernText shell (bash-style)Object shell (PowerShell)
Unit passed on the pipeA flat string of bytesA typed object with named members
Selecting one fieldCount columns with cut or awkAddress it by name such as .Qty
Numeric workReparse digits and hope for no commasThe property is already a number
Discovering structureRead external docs or guessPipe the object into Get-Member

The Verb-Noun Contract

PowerShell ships a fixed list of approved verbs grouped by intent (Common, Lifecycle, Data, and more). Authors are expected to choose from that list, which is why unfamiliar cmdlets stay guessable. Get-Verb prints the catalogue.

'{0,-8}{1}' -f 'Verb', 'Group'
'{0,-8}{1}' -f '----', '-----'
Get-Verb -Verb Get, Set, New, Stop, Restart |
    ForEach-Object { '{0,-8}{1}' -f $_.Verb, $_.Group }

Output:

Verb    Group
----    -----
Get     Common
Set     Common
New     Common
Stop    Lifecycle
Restart Lifecycle

Because verbs are standardised, Get always reads without side effects, Set mutates existing state, New creates, and Stop and Restart belong to lifecycle control. Learning the roughly one hundred approved verbs teaches you the shape of thousands of cmdlets you have never run.


Real World Example: Auditing a Fixed Inventory of Services

Suppose you are handed a machine's service inventory as a fixed table and asked three questions: which running services use the most memory, how much memory they use in total, and how many are running at all. In a text shell you would scrape a printed report with cut and awk and hope the columns never shift. In PowerShell you keep the records as objects and let each stage of the pipeline address the fields it needs by name. The script below starts from a fixed sample array, so the result is identical on every run, and then answers all three questions from the same set of objects.

$inventory = @(
  [PSCustomObject]@{ Name = 'Spooler'; Status = 'Running'; StartMode = 'Auto';   MemoryMB = 18 }
  [PSCustomObject]@{ Name = 'W32Time'; Status = 'Stopped'; StartMode = 'Manual'; MemoryMB = 6  }
  [PSCustomObject]@{ Name = 'BITS';    Status = 'Running'; StartMode = 'Manual'; MemoryMB = 24 }
  [PSCustomObject]@{ Name = 'WinRM';   Status = 'Running'; StartMode = 'Auto';   MemoryMB = 31 }
  [PSCustomObject]@{ Name = 'Themes';  Status = 'Stopped'; StartMode = 'Auto';   MemoryMB = 12 }
)

$sum   = ($inventory | Where-Object { $_.Status -eq 'Running' } | Measure-Object MemoryMB -Sum).Sum
$count = ($inventory | Where-Object { $_.Status -eq 'Running' }).Count

Write-Output ('Running service count: ' + $count)
Write-Output ('Total memory of running services (MB): ' + $sum)
Write-Output ''
Write-Output 'Running services, largest memory first:'

$inventory |
  Where-Object { $_.Status -eq 'Running' } |
  Sort-Object MemoryMB -Descending |
  Select-Object Name, MemoryMB |
  Format-Table -AutoSize

Output:

Running service count: 3
Total memory of running services (MB): 73

Running services, largest memory first:

Name    MemoryMB
----    --------
WinRM         31
BITS          24
Spooler       18

Read the pipeline from left to right as a chain of stages that each receive objects and pass objects on. $inventory emits five service objects; Where-Object keeps only the three whose Status property equals Running; Sort-Object reorders those three by MemoryMB in descending order; Select-Object narrows each surviving object to the two columns worth displaying; and Format-Table renders the result as an aligned grid. At no point did a stage slice a substring or count a column to find a field.

The two summary lines lean on the same objects. Measure-Object MemoryMB -Sum walks the running services and adds their MemoryMB values as genuine integers, producing 73 rather than a run-together string of digits, and .Count on the filtered collection returns a real integer of 3. Because these are numbers and not text, you could feed them straight into further arithmetic, a comparison, or a threshold alert with no reparsing step in between.

The script does carry one real weakness worth naming. The identical filter Where-Object { $_.Status -eq 'Running' } is written and executed three separate times: once for the sum, once for the count, and once for the table. On five rows the waste is invisible, but against a live inventory of thousands of services it triples the filtering work, and worse it opens a correctness gap: if the underlying data changed between the first filter and the third, the count, the total, and the table could each describe a slightly different population. The disciplined fix is to filter once into a variable, $running = $inventory | Where-Object { $_.Status -eq 'Running' }, and then read $running.Count, pipe $running into Measure-Object, and pipe $running into Sort-Object from that single snapshot, which is both faster and internally consistent.


Common Mistakes

  1. Treating command output as text. Reaching for substring math or -split to pull a value out of what a cmdlet printed, when the value is already a named property you can read with a dot. The screen rendering is a courtesy; the object is the real result.
  2. Reading a property with parentheses or calling a method without them. $s.Length() fails because Length is a property, and $s.ToUpper returns the method itself instead of running it because the parentheses are missing. Properties take a bare dot; methods need ().
  3. Confusing Select-Object with Where-Object. Select-Object chooses which columns survive on each object; Where-Object chooses which objects survive at all. Swapping them either drops rows you wanted or keeps columns you meant to discard.
  4. Using == or = to compare. PowerShell compares with -eq; a single = is assignment and == is not an operator at all. Writing if ($x = 5) silently assigns instead of testing.
  5. Forgetting $_ inside a script block. Within Where-Object { } or ForEach-Object { } the current pipeline object is $_ (also spelled $PSItem); omitting it leaves the block with nothing to test.
  6. Inventing unapproved verbs. Naming a function Fetch-Data or Grab-Log instead of Get-Data breaks discoverability and makes the module emit a warning on import. Stick to the list that Get-Verb returns.
  7. Piping Format-Table output onward. The Format-* cmdlets emit formatting instructions, not data, so sending their output into Where-Object, Export-Csv, or ConvertTo-Json produces garbage. Format last, or not at all in a pipeline meant to be processed.
  8. Assuming -eq always returns a boolean. When the left side is a collection, -eq filters the collection and returns the matching elements, not $true or $false. Guard with .Count or -contains when you need a yes-or-no answer.
  9. Quoting numbers into strings by accident. Wrapping a value in quotes makes '42' + 1 perform string concatenation and yield 421. Keep numeric properties numeric so arithmetic and sorting behave as expected.

Best Practices

  • Keep data as objects and format last. Let objects flow through the whole pipeline and apply Format-Table or Format-List only at the final display step; when another program needs the data, reach for Export-Csv or ConvertTo-Json instead.
  • Discover before you script. Pipe unfamiliar output into Get-Member to see its real type and members, and read Get-Help <cmdlet> -Examples rather than guessing at parameter names.
  • Address fields by name, never by position. Use .PropertyName and Select-Object Name, Status so that a change in column order or width can never silently break a script.
  • Follow the Verb-Noun contract in your own code. Name functions with an approved verb and a singular noun, such as Get-DiskReport, so callers can guess and discover them the same way they discover built-in cmdlets.
  • Filter once and reuse the result. Capture an expensive Where-Object into a variable and read the count, the sum, and the sorted view from that one snapshot instead of re-filtering for each.
  • Filter left, format right. Place Where-Object and Select-Object -First as early in the pipeline as possible so that later, heavier stages operate on the smallest set of objects.
  • Prefer full cmdlet names in saved scripts. Terse aliases such as gci, iwr, and cd are convenient at the prompt but hurt readability; spell out Get-ChildItem, Invoke-WebRequest, and Set-Location in code you commit.
  • Return structured results with [PSCustomObject]. When a function produces records, emit typed objects with named properties so that callers can pipe, sort, filter, and select them exactly like any other cmdlet output.

Practice Exercises

  1. Inspect a real object. Run Get-Process | Select-Object -First 1 | Get-Member and write down three properties and three methods it exposes, noting for each whether it represents data the object holds or behaviour it can perform.
  2. Build and read a custom object. Create a [PSCustomObject] describing a book with Title, Author, and Pages, then print a sentence that reads the Pages property and computes an estimated reading time at forty pages per hour.
  3. Filter, sort, and select. Given a fixed array of five [PSCustomObject] files with Name and SizeKB properties, produce a table of only the files larger than one hundred KB, sorted largest first, showing just Name and SizeKB.
  4. Refactor the audit script. Take the services example from this lesson and rewrite it so the running services are filtered once into a $running variable, then derive the count, the total memory, and the sorted table from that single variable, and confirm the printed result is identical.