In many shells the output of a command is text, and the next command has to take this text apart again with grep, awk or cut. PowerShell does it differently: a command returns objects, and the pipeline passes these objects unchanged to the next one. That saves the taking apart and makes scripts robust, because a column is no longer “the third word in the line” but a named property. This lesson shows it with a small practice folder.

The practice folder

All examples of this lesson run in a folder that a script creates anew. It lies in the temporary directory, contains five files of different sizes and carries the names of an invented company, Nordlicht Reisen GmbH:

PowerShell
$root = Join-Path ([IO.Path]::GetTempPath()) 'nordlicht-uebung'
if (Test-Path -LiteralPath $root) { [IO.Directory]::Delete($root, $true) }
New-Item -ItemType Directory $root | Out-Null
$files = [ordered]@{ 'bericht-nord.txt'=120; 'bericht-sued.txt'=480; 'preise.csv'=300; 'notizen.md'=50; 'bericht-west.txt'=900 }
foreach ($n in $files.Keys) { Set-Content (Join-Path $root $n) ('x' * $files[$n]) -NoNewline }

The number after each name is the size of the file in bytes. -NoNewline keeps Set-Content from appending a line break so that the size is right. The cleanup at the end ([IO.Directory]::Delete($root, $true)) belongs to every exercise that creates the folder; it deletes only this one folder that you created yourself.

Everything is an object

PowerShell
$f = Get-ChildItem $root
$f.GetType().FullName
$f[0].GetType().FullName
System.Object[]
System.IO.FileInfo

Get-ChildItem returned five objects in an array (System.Object[]), and each element is a System.IO.FileInfo: a .NET type that knows everything the file system says about a file. Properties are values of the object (Name, Length, LastWriteTime), methods are things it can do (Delete(), CopyTo(…)). What an object has is revealed by Get-Member:

PowerShell
$f | Get-Member -MemberType Property | Select-Object -First 4 Name, TypeName | Format-Table -AutoSize
Name            TypeName
----            --------
Attributes      System.IO.FileInfo
CreationTime    System.IO.FileInfo
CreationTimeUtc System.IO.FileInfo
Directory       System.IO.FileInfo

The column TypeName names the type the properties belong to (here always FileInfo). The command shows the first four of many. Get-Member is your tool number one when you do not know what a command returns: append | Get-Member and read. The same goes for methods and properties of strings and dates:

PowerShell
'nordlicht'.ToUpper()
'nordlicht'.Length
(Get-Date '2025-03-01').AddDays(10).ToString('yyyy-MM-dd')
NORDLICHT
9
2025-03-11

The pipeline

The vertical bar | connects commands: everything the left command outputs goes, object by object, to the right one. Five cmdlets cover everyday work.

Where-Object filters. The objects for which the condition holds are kept:

PowerShell
Get-ChildItem $root | Where-Object Length -gt 200 | Sort-Object Length -Descending | Select-Object Name, Length
Name             Length
----             ------
bericht-west.txt    900
bericht-sued.txt    480
preise.csv          300

The short form Where-Object Length -gt 200 (property, operator, value) is enough for simple conditions; for compound ones you take a script block with $_ as the current object: Where-Object { $_.Length -gt 200 -and $_.Extension -eq '.txt' }. You learn the comparison operators (-gt, -eq, -like) in more detail in lesson PS.2.1.

Sort-Object sorts, Select-Object picks properties (or the first and last objects, see below). Group-Object groups and Measure-Object calculates:

PowerShell
Get-ChildItem $root | Group-Object Extension | Select-Object Name, Count | Sort-Object Name
(Get-ChildItem $root | Measure-Object Length -Sum -Average).Sum
Name Count
---- -----
.csv     1
.md      1
.txt     3

1850

Measure-Object returns an object with Count, Sum, Average, Minimum and Maximum; here we took out only the sum.

ForEach-Object runs code for each object, with $_ as the object:

PowerShell
Get-ChildItem $root | ForEach-Object { '{0} hat {1} Bytes' -f $_.Name, $_.Length }

The format '{0} hat {1} Bytes' -f … fills placeholders (the text “hat … Bytes” is German, as in the practice names). If you know a cmdlet for the task, prefer it over ForEach-Object: it is shorter and more readable.

Calculated properties

Sometimes the column you need is missing: the size should be in kilobytes, and the column should be called KB. For this Select-Object takes a hashtable with Name (n) and Expression (e):

PowerShell
Get-ChildItem $root |
    Select-Object Name, @{ n = 'KB'; e = { [math]::Round($_.Length / 1KB, 2) } } |
    Sort-Object Name
Name               KB
----               --
bericht-nord.txt 0,12
bericht-sued.txt 0,47
bericht-west.txt 0,88
notizen.md       0,05
preise.csv       0,29

The decimal comma comes from the language setting of this machine (German); on yours there may be a period. 1KB is a shorthand for 1024. The result is again a list of objects, only with the new property: you can keep filtering, sorting and summing.

Format commands are only for the eyes

Format-Table, Format-List and Format-Wide prepare output for the screen. They do not turn objects into better objects, they produce formatting instructions. A rule with a trap follows from this:

PowerShell
$x = Get-ChildItem $root | Format-Table Name
$x[0].GetType().FullName
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData

$x now contains no files any more but format objects (FormatStartData and more) that no command after it can do anything with. That is why a Format-* always stands at the very end of the pipeline, and never in a function that is meant to return data. Whoever needs data takes Select-Object; whoever wants it pretty on the screen formats at the very end. (For the course text we appended an Out-String or a Format-List to the format command so that the example appears as text in the script.)

Select-Object -First and its consequence

Select-Object -First 2 takes the first two objects and then ends the pipeline. That is handy with long lists, but it has an effect on the command before it:

PowerShell
1..5 | ForEach-Object { Write-Host "erzeugt $_"; $_ } | Select-Object -First 2
erzeugt 1
1
erzeugt 2
2

The command before it is stopped after the second object: “erzeugt 3” never appears (“erzeugt” is German for “produced”). With a harmless loop that is good. With a command that changes something or whose exit code you still need (an external program, see lesson PS.2.3) it is a trap: you see only a part, and $LASTEXITCODE belongs to the command that ran before. Remember: -First only on commands that change nothing and whose end you do not need.

Output and streams

PowerShell has several output streams: success (stream 1, the data), error (2), warning (3), verbose (4), debug (5) and information (6). Only the success stream runs through the pipeline. Messages for humans belong in the others:

PowerShell
function T { Write-Output 'daten'; Write-Warning 'warn'; Write-Verbose 'v' -Verbose; Write-Information 'info' -InformationAction Continue }
$r = T 3>$null 4>$null 6>$null
$r
daten

3>$null sends the warning stream into nothing, 4> the verbose stream, 6> the information stream. What remains is what belongs in the pipeline: daten. Whoever outputs data with Write-Host in a function takes this data away from the caller, because Write-Host is not part of the pipeline. Data belongs to Write-Output (or simply as a value on the line), messages to Write-Verbose, Write-Warning or Write-Information. In lesson PS.2.2 you see how a function puts that into practice.

Output to files

Out-File (or the redirection >) writes the formatted output to a file, that is, what you would see on the screen. For data that another program is to read, take Export-Csv or ConvertTo-Json (lesson PS.1.3) instead, because they write the objects without loss.

Exercise 1: Read the pipeline

Create the practice folder (script above).

  1. Which files are larger than 400 bytes? Show Name and Length, largest first.
  2. How many files are there per extension, and how many bytes in total per extension?
  3. How do you get the size in kilobytes with one decimal place in a column of its own called KB?

Solution 1

  1. Get-ChildItem $root | Where-Object Length -gt 400 | Sort-Object Length -Descending | Select-Object Name, Length. Result: bericht-west.txt (900) and bericht-sued.txt (480).
  2. Get-ChildItem $root | Group-Object Extension | ForEach-Object { [pscustomobject]@{ Endung = $_.Name; Anzahl = $_.Count; Bytes = ($_.Group | Measure-Object Length -Sum).Sum } }. Each group has the property Group with the objects; [pscustomobject]@{…} creates a new object (lesson PS.2.1).
  3. Select-Object Name, @{ n = 'KB'; e = { [math]::Round($_.Length / 1KB, 1) } }.

Exercise 2: Experience the format problem

  1. Run $x = Get-ChildItem $root | Format-Table Name and read $x[0].GetType().FullName. What do you notice?
  2. Write a function Get-GrosseDateien that returns files over 400 bytes, once with Format-Table at the end, once without. How do (Get-GrosseDateien).Count and (Get-GrosseDateien | Select-Object -First 1).Name differ?
  3. Where does Format-Table belong?

Solution 2

  1. The first object is a FormatStartData, not a file.
  2. Without Format-Table, .Count is 2 and .Name is bericht-sued.txt; with Format-Table, .Count is 6 (format objects are counted, not files) and .Name is empty, because the function returns format objects.
  3. At the top level of your call, at the very end, for display only.

Exercise 3: -First and the streams

  1. Write a pipeline 1..5 | ForEach-Object { Write-Host "erzeugt $_"; $_ } | Select-Object -First 2 and describe what happens.
  2. Which data stays in $r when the function T from the section “Output and streams” is called without the redirections: $r = T? Try it and explain where the warning, the verbose line and the information go.

Solution 3

  1. “erzeugt 1”, 1, “erzeugt 2”, 2; the rest no longer runs.
  2. $r contains only daten. Warning, verbose line and information appear on the screen (the warning is preceded by “WARNING: warn” or the equivalent in your system language), but they are not part of the return value.

(Afterwards: [IO.Directory]::Delete($root, $true) cleans up the practice folder.)

What you can do now

  • You explain that PowerShell passes objects on, and you read with Get-Member what an object can do.
  • You filter, sort, group, count and sum with Where-Object, Sort-Object, Group-Object, Measure-Object, Select-Object.
  • You build calculated properties.
  • You put Format-* at the end and return only objects from functions.
  • You know that Select-Object -First stops the command before it.
  • You tell data (success stream) from messages (warning, verbose, information).

The next lesson goes to the things these objects point to: files, environment variables and structured data.

Further reading