Loading
0x30Lesson 4 of 17

Files, folders and providers

Navigate and manage files with the *-Item and *-Content cmdlets, and explore other drives like Env:.

26 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • Move around with Get-Location and Set-Location, and list with Get-ChildItem
  • Create, copy, move, rename and remove items - safely, with -WhatIf
  • Read and write files with Get-Content, Set-Content and Add-Content, and use providers like Env:

PowerShell manages files with a small family of cmdlets that share nouns:

CmdletDoesFamiliar alias
Get-Locationwhere am I?pwd
Set-Locationgo somewherecd
Get-ChildItemlist (-Recurse, -Filter *.log, -File, -Directory, -Force for hidden)ls, dir, gci
New-Itemcreate a file or folder (-ItemType Directory)ni, mkdir
Copy-Item / Move-Item / Rename-Itemcopy, move, renamecp, mv, ren
Remove-Itemdelete (-Recurse for folders)rm, del
Test-Pathdoes it exist? ($true/$false)
Join-Pathbuild a path with the right separator

Paths use \ on Windows and / elsewhere - and PowerShell accepts either on Windows. Join-Path picks the right one, which keeps scripts portable.

enclosures.ps1
1$root = Join-Path ([IO.Path]::GetTempPath()) "emberfall-$(Get-Random)"
2New-Item -ItemType Directory -Path $root | Out-Null
3Set-Location $root
4New-Item -ItemType Directory -Path 'north-tower', 'cave' | Out-Null
5New-Item -ItemType File -Path 'cave/mossback.txt', 'cave/pebble.txt' | Out-Null
6Copy-Item 'cave/pebble.txt' 'north-tower/pebble-backup.txt'
7Rename-Item 'cave/mossback.txt' 'old-mossback.txt'
8Get-ChildItem -Recurse -File | Sort-Object Name | ForEach-Object Name
9Test-Path 'cave/mossback.txt'
10(Get-ChildItem -Directory).Count
Output
old-mossback.txt
pebble-backup.txt
pebble.txt
False
2

Two things to notice:

  • | Out-Null throws away output you don’t want - New-Item would otherwise print a listing of everything it created.
  • The script never prints a full path, because temporary folders have random names. It prints Names instead.

Reading and writing files

  • Set-Content file.txt 'text' writes (replacing what was there); Add-Content appends.
  • Get-Content file.txt returns the file as an array of lines - so (Get-Content file.txt).Count counts lines and [0] is the first one. -Raw gives one big string instead; -TotalCount 5 reads just the first 5 lines and -Tail 5 the last 5.
  • Careful: a file with exactly one line comes back as a plain string, not an array, so [0] would give its first character. Wrap the call in the array operator, @(Get-Content file.txt), whenever you index into the lines.
  • Out-File and the redirection operators > and >> save formatted output, like the console shows it. For data, prefer Set-Content, or Export-Csv and ConvertTo-Json (coming up).
feeding-log.ps1
1$log = Join-Path ([IO.Path]::GetTempPath()) "feeding-$(Get-Random).txt"
2Set-Content -Path $log -Value '07:00 Ember: 4 goats'
3Add-Content -Path $log -Value '07:30 Glim: 1 lantern moth', '08:00 Skyla: 6 fish'
4$lines = Get-Content -Path $log
5"$($lines.Count) feedings, first: $($lines[0])"
6Get-Content -Path $log -Tail 1
7Remove-Item $log
8Test-Path $log
Output
3 feedings, first: 07:00 Ember: 4 goats
08:00 Skyla: 6 fish
False

Providers: drives that aren’t disks

The same *-Item cmdlets work on more than files. Providers present other data stores as drives:

DriveContainsTry
C:, /the filesystemGet-ChildItem C:\
Env:environment variablesGet-ChildItem Env:, $env:PATH
Variable:your PowerShell variablesGet-ChildItem Variable:
Function:loaded functionsGet-ChildItem Function:
HKLM:, HKCU:the Windows registryGet-ChildItem HKCU:\Software
Cert:Windows certificate storesGet-ChildItem Cert:\CurrentUser\My

Get-PSDrive lists them all. Environment variables are handy enough to have their own syntax: $env:NAME reads one and $env:NAME = 'value' sets it for this session.

providers.ps1
1$env:SANCTUARY = 'Emberfall'
2"Hello from $env:SANCTUARY"
3Test-Path Env:SANCTUARY
4(Get-Item Env:SANCTUARY).Value.Length
5Remove-Item Env:SANCTUARY
6Test-Path Env:SANCTUARY
Output
Hello from Emberfall
True
9
False

Key takeaways

  • Get/Set-Location, Get-ChildItem and the *-Item cmdlets navigate and manage files.

  • Use -WhatIf to rehearse changes and Join-Path to build portable paths.

  • Get-Content returns lines; Set-Content replaces, Add-Content appends.

  • Providers expose Env:, Variable:, the registry and more as drives with the same cmdlets.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write PowerShell scripts

Write a script in the editor and run it for real against sample input, which is piped into your script as $input. Scripts run on PowerShell 6.2 through Try It Online (tio.run), a free public service, so these exercises avoid PowerShell 7-only syntax; your script and test input are sent there.

Exercise 1

Build the enclosures

+25 XP

The starter creates an empty sanctuary folder and moves into it. Create:

  • folders volcano and lagoon
  • empty files volcano/ember.txt, volcano/cinder.txt and lagoon/skyla.txt

Then the provided lines print every file name (sorted) and the number of folders. Hide New-Item’s own output with | Out-Null.

  • Builds the enclosures
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Exercise 2

Feeding journal

+25 XP

Each input line is a feeding record. Write them all to a journal file in a temporary folder - the first with Set-Content, the rest with Add-Content, or all at once - then print entries: N, the first line and the last line of the file, read back with Get-Content.

  • Morning feedings
  • One feeding
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: