Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 34 ยท Files, Data and Errors

Working with Files and Folders

Learn how PowerShell works with files and folders: providers, Get-ChildItem, Copy-Item, Move-Item, Remove-Item, Test-Path, Get-Content and Set-Content.

Almost every script touches the file system sooner or later: find the logs older than a month, copy a build into a release folder, write a report, read a settings file. PowerShell handles all of this with a small family of cmdlets that return objects, not text. A file is a FileInfo object with a Length, a LastWriteTime and an Extension, so you can filter and sort files with the tools you already know from Where-Object, Select-Object and Sort-Object.

The cmdlets in this lesson are not limited to disks. They talk to PowerShell providers, which let the same commands navigate the registry, environment variables and more. The real commands below are read-only because the site cannot touch your disk. To practice the ideas, the runnable examples use a JavaScript virtual file system, a stand-in that follows the same rules but lives in memory.

Providers and drives

A provider exposes a data store as a drive with a tree of items. Get-PSProvider lists them and Get-PSDrive lists the drives they created.

One syntax, many stores

FileSystem Drives such as C: and D:, or / on Linux.
Registry HKLM: and HKCU: on Windows.
Environment The Env: drive holds variables.
Variable and Function Even your own variables form a drive.

Learn the cmdlets once, use them everywhere.

1 / 2
POWERSHELL
Get-PSProvider
Get-ChildItem Env:            # environment variables, listed like files
Get-ChildItem HKCU:\Software  # registry keys (Windows only)
Set-Location Env:
Get-Item PATH

This is why the cmdlet names say Item instead of File: an item can be a file, a folder, a registry key or a variable. The file-specific bits (-File, -Directory, Get-Content) only work with the FileSystem provider.

Listing with Get-ChildItem

Get-ChildItem (aliases gci, ls, dir) lists the contents of a location. With no argument it uses the current folder. These parameters cover most needs:

POWERSHELL
Get-ChildItem C:\Logs                       # one folder
Get-ChildItem C:\Logs -Recurse              # every level below
Get-ChildItem C:\Logs -File                 # files only (-Directory for folders)
Get-ChildItem C:\Logs -Filter *.log         # fast, filtered by the file system
Get-ChildItem C:\Logs -Recurse -Include *.log, *.txt
Get-ChildItem C:\Logs -Force                # include hidden and system items

-Filter is applied by the provider while it reads the folder and accepts a single simple pattern, which makes it the fast choice. -Include is applied by PowerShell afterwards, accepts several patterns, and only works well together with -Recurse or a wildcard in the path. For anything more complex, pipe to Where-Object:

POWERSHELL
Get-ChildItem C:\Logs -Recurse -File |
  Where-Object { $_.Length -gt 1MB -and $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
  Sort-Object Length -Descending |
  Select-Object FullName, @{ Name = 'MB'; Expression = { [math]::Round($_.Length / 1MB, 1) } }

Notice 1MB: PowerShell understands the suffixes KB, MB, GB, TB and PB in numeric literals.

Creating, copying, moving and removing

POWERSHELL
New-Item -ItemType Directory -Path C:\Work\reports        # creates parents too
New-Item -ItemType File -Path C:\Work\reports\todo.txt
Copy-Item C:\Work\reports\todo.txt C:\Work\backup\        # file into a folder
Copy-Item C:\Work\reports C:\Work\reports-copy -Recurse   # whole tree
Move-Item C:\Work\reports\todo.txt C:\Work\archive\
Rename-Item C:\Work\archive\todo.txt done.txt
Remove-Item C:\Work\reports-copy -Recurse -Force

Three habits keep you safe:

  • Preview destructive commands with -WhatIf. Remove-Item C:\Work\* -Recurse -WhatIf prints what it would delete and deletes nothing. You will build your own -WhatIf support in Advanced Functions.
  • Use -Confirm when you want a prompt for each item.
  • There is no recycle bin. Remove-Item deletes permanently.

The -Path parameter treats *, ? and [ ] as wildcards. A file literally named report[1].txt will not be found with -Path; use -LiteralPath to turn wildcards off.

Paths and Test-Path

Build paths with cmdlets instead of string concatenation, so separators are always right on Windows, Linux and macOS:

POWERSHELL
$dir  = Join-Path $env:TEMP 'demo'
$file = Join-Path $dir 'notes.txt'
Split-Path $file -Parent        # the folder part
Split-Path $file -Leaf          # notes.txt
[IO.Path]::GetExtension($file)  # .txt
Test-Path $file                 # $true or $false
Test-Path $dir -PathType Container

Test-Path returns a Boolean instead of raising an error for a missing item, which makes it the standard guard before reading or creating. Inside a script, $PSScriptRoot gives the folder the script lives in, which is better than assuming the current location (see Scripts and Execution Policy).

Reading and writing text

POWERSHELL
Get-Content app.log                # array of lines (strings)
Get-Content app.log -TotalCount 5  # first 5 lines
Get-Content app.log -Tail 20       # last 20 lines
Get-Content app.log -Wait          # keep reading as lines are appended
Get-Content app.log -Raw           # one single string
Set-Content out.txt 'first line'   # create or REPLACE the file
Add-Content out.txt 'second line'  # append
'x' | Out-File out.txt -Append

Get-Content emits each line as a separate string, so (Get-Content app.log).Count is the line count. Add -Raw when you want one string, for instance before a regular expression that spans lines or before ConvertFrom-Json.

Encoding matters when files cross tools. PowerShell 7 writes UTF-8 without a byte-order mark by default. Windows PowerShell 5.1 differs: Set-Content uses the system ANSI code page and Out-File (and the > operator) writes UTF-16. When a file must read the same everywhere, pass -Encoding utf8 explicitly.

Practice with a virtual file system

This stand-in keeps a tree in memory and offers functions named after the cmdlets. It is not PowerShell and does not touch your disk, but the rules it shows match the real cmdlets: Copy-Item into an existing folder puts the copy inside it, -Filter takes one pattern, and creating a file (as opposed to a folder) in a parent that does not exist is an error.

JS A virtual file system: Get-ChildItem, Copy-Item, Move-Item

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output from the top: the first listing shows files and folders together (the d----- and -a---- markers imitate the Mode column that Get-ChildItem prints); the recursive filter finds the log files at every depth. After the copy and move, /logs/old is gone, so Test-Path reports false, and creating a file in a folder that does not exist fails with an error instead of silently inventing the folder.

Reading, writing and appending

The second stand-in models how the text cmdlets treat lines. The point is the difference between replacing and appending, and between an array of lines and one raw string.

JS Set-Content, Add-Content and Get-Content

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Set-Content after two appends leaves only one line, which is exactly the surprise people hit with a second Set-Content call. The model is a teaching aid: real cmdlets also deal with encodings, file locks and large files that stream line by line instead of loading everything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are the file cmdlets named Get-ChildItem and Copy-Item instead of Get-ChildFile?

    Providers expose different data stores through the same cmdlets, so the nouns describe items in general. File-specific switches like -File only apply to the FileSystem provider.
  2. 2. What is the difference between -Filter and -Include on Get-ChildItem?

    -Filter lets the file system do the work, so it is quick but limited to one simple pattern. -Include is processed by PowerShell and accepts a list of patterns.
  3. 3. You run Set-Content log.txt 'two' on a file that already holds ten lines. What does the file contain?

    Set-Content replaces the whole content. Use Add-Content (or Out-File -Append) to add a line at the end.
  4. 4. A file is named report[1].txt and Get-Item -Path cannot find it. What is the fix?

    -Path interprets [ ] as wildcard characters. -LiteralPath takes the text exactly as written.
  5. 5. What does Remove-Item C:\Temp\old -Recurse -WhatIf do?

    -WhatIf is a safety switch: the cmdlet reports the actions it would take and then stops.

Summary

  • Providers expose file systems, the registry, environment variables and more through the same cmdlets, which is why they talk about items.
  • Get-ChildItem lists items; use -Recurse, -File, -Directory, -Filter (fast, one pattern) and -Include (several patterns), then filter further with Where-Object.
  • New-Item, Copy-Item, Move-Item, Rename-Item and Remove-Item do the work; test with -WhatIf first, because deletion is permanent.
  • Build paths with Join-Path and Split-Path, guard with Test-Path, and use -LiteralPath for names containing [ ].
  • Get-Content returns lines (or one string with -Raw), Set-Content replaces, Add-Content appends; pass -Encoding when files cross tools.

Next, turn text files into objects in CSV, JSON and XML.