Working with Files and Folders
Find, create, copy, move, read, write, archive, hash and watch files in PowerShell, including the -Filter vs -Include trap and the encoding change between 5.1 and 7.
By The Dark DebuggerUpdated 35 min read
This article covers the file system work that most PowerShell scripts end up doing: listing and filtering files, testing paths, creating, copying, moving and deleting safely, reading and writing text (and the encoding change between Windows PowerShell 5.1 and 7), path manipulation, timestamps and attributes, finding big or old files, zip archives, hashes, and watching a folder for new files. It assumes you know the pipeline, loops and functions with -WhatIf. Next comes CSV, JSON, and XML, which builds on reading and writing files.
Why this matters
Two situations come up constantly. A server's disk fills up because nobody rotated the
application logs. And a Downloads folder (or a shared drop folder) holds 2,000 files that
someone needs sorted, de-duplicated or cleaned out. Both are a dozen lines of PowerShell,
if you know which parameters bite. -Include silently returns nothing without
-Recurse. A folder name with [brackets] makes Remove-Item do nothing. Out-File in
5.1 writes UTF-16 files that Linux tools choke on. This article walks through each of
those, then builds both scripts.
Every example was run with pwsh -NoProfile -File on PowerShell 7.6.9 (Linux), in a folder
with a downloads, logs and project directory. Windows-only behaviour was checked in
Windows PowerShell 5.1 on Windows 11, using only files in a scratch folder. The large files
in downloads are sparse test files, so their sizes are real as far as PowerShell is
concerned, but they hold no data.
Listing files with Get-ChildItem
Get-ChildItem (aliases gci, ls, dir) lists a folder. On Linux and macOS, PowerShell 7
shows Unix-style columns:
Get-ChildItem -Path ./project Directory: /home/sid/files/project
UnixMode User Group LastWriteTime Size Name
-------- ---- ----- ------------- ---- ----
drwxr-xr-x sid sid 11/10/2026 01:29 4096 build
drwxr-xr-x sid sid 11/10/2026 01:29 4096 docs
drwxr-xr-x sid sid 11/10/2026 01:29 4096 src
drwxr-xr-x sid sid 11/10/2026 01:29 4096 testsOn Windows you get Mode, LastWriteTime, Length and Name. Either way, these are
FileInfo and DirectoryInfo objects, so you choose what to show:
Get-ChildItem -Path ./downloads -File | Format-Table -Property LastWriteTime, Length, NameLastWriteTime Length Name
------------- ------ ----
08/14/2026 18:30:00 3276800 holiday-photo.jpg
09/21/2026 11:02:00 2867200 IMG_2041.jpeg
09/21/2026 11:03:00 2969600 IMG_2042.jpeg
10/03/2026 09:12:00 250880 invoice-2026-10.pdf
11/02/2026 08:47:00 257024 invoice-2026-11.pdf
11/05/2026 10:30:00 36864 meeting-notes.docx
11/08/2026 21:05:00 65 notes.txt
06/11/2026 07:15:00 7577600 podcast-ep12.mp3
10/15/2026 14:45:00 90112 report-q3.xlsx
11/10/2026 01:29:31 25 report[final].txt
11/07/2026 16:20:00 419840 screenshot.png
07/01/2026 10:00:00 50331648 setup-tool.zip
11/10/2026 01:29:31 81 SHA256SUMSThe switches you'll use daily:
(Get-ChildItem -Path ./downloads -Directory).Name
'--- -File, first four:'
(Get-ChildItem -Path ./downloads -File | Select-Object -First 4).Name
'--- -Force also shows hidden items:'
(Get-ChildItem -Path ./downloads -File -Force | Where-Object Name -like '.*').Name
'--- -Hidden shows only hidden items:'
(Get-ChildItem -Path ./downloads -Hidden).Nameold
--- -File, first four:
holiday-photo.jpg
IMG_2041.jpeg
IMG_2042.jpeg
invoice-2026-10.pdf
--- -Force also shows hidden items:
.hidden-config
--- -Hidden shows only hidden items:
.hidden-configOn Linux, PowerShell treats dot-files as hidden. On Windows it's the Hidden attribute.
Either way, Get-ChildItem skips hidden items unless you add -Force, so a cleanup script
without -Force silently leaves them behind.
-Filter, -Include and -Exclude
This is the most common Get-ChildItem trap. -Filter is passed to the file system and is
fast. -Include and -Exclude are applied by PowerShell afterwards, and -Include only works
when the path has a wildcard or when you use -Recurse:
(Get-ChildItem -Path ./downloads -Filter *.pdf).Name
'--- -Include without -Recurse or a wildcard:'
(Get-ChildItem -Path ./downloads -Include *.pdf, *.docx).Name
'--- -Include with a wildcard path:'
(Get-ChildItem -Path ./downloads/* -Include *.pdf, *.docx).Name
'--- -Exclude:'
(Get-ChildItem -Path ./downloads/* -Exclude *.pdf, *.jp*g -File).Nameinvoice-2026-10.pdf
invoice-2026-11.pdf
--- -Include without -Recurse or a wildcard:
--- -Include with a wildcard path:
invoice-2026-10.pdf
invoice-2026-11.pdf
meeting-notes.docx
--- -Exclude:
meeting-notes.docx
notes.txt
podcast-ep12.mp3
report-q3.xlsx
report[final].txt
screenshot.png
setup-tool.zip
SHA256SUMSThe second command returned nothing, with no error. -Filter takes exactly one pattern;
-Include and -Exclude take several. The speed difference is real. I timed it on a tree of
3,000 files in 150 folders, kept in memory (/dev/shm) so the disk wasn't measured:
$root = '/dev/shm/ps-c/tree'
"files in tree: $((Get-ChildItem -Path $root -Recurse -File).Count)"
$filter = Measure-Command { $a = Get-ChildItem -Path $root -Recurse -Filter *.log }
$include = Measure-Command { $b = Get-ChildItem -Path $root -Recurse -Include *.log }
$where = Measure-Command { $c = Get-ChildItem -Path $root -Recurse | Where-Object Extension -eq '.log' }
'-Filter {0,5:N0} ms ({1} files)' -f $filter.TotalMilliseconds, $a.Count
'-Include {0,5:N0} ms ({1} files)' -f $include.TotalMilliseconds, $b.Count
'Where-Object {0,5:N0} ms ({1} files)' -f $where.TotalMilliseconds, $c.Countfiles in tree: 3000
-Filter 24 ms (750 files)
-Include 182 ms (750 files)
Where-Object 205 ms (750 files)-Filter was about seven times faster, because the other two create an object for every file
and then throw most of them away. On a network share with a million files, that's the
difference between seconds and minutes. Use -Filter for one pattern, and add -Include or
Where-Object only when you need more than one.
On Windows, -Filter has a legacy quirk inherited from 8.3 short file names: a
three-character extension also matches longer ones. In Windows PowerShell 5.1, with
index.htm, index.html and about.html in a folder:
(Get-ChildItem -Path . -Filter *.htm).Name
'---'
(Get-ChildItem -Path ./* -Include *.htm).Nameabout.html
index.htm
index.html
---
index.htmIf the exact extension matters on Windows, for example when deleting *.log but not
*.log1, use -Include or check $_.Extension -eq '.log'.
-Recurse and -Depth
-Recurse walks the whole tree. -Depth limits how far, where 0 means the folder itself.
Piping to Resolve-Path -Relative gives readable paths:
Get-ChildItem -Path ./project -Recurse -File | Resolve-Path -Relative
'--- -Depth 1:'
Get-ChildItem -Path ./project -Recurse -Depth 1 | Resolve-Path -Relative
'--- skipping build output:'
Get-ChildItem -Path ./project -Recurse -File |
Where-Object FullName -notmatch '[\\/]build[\\/]' |
Resolve-Path -Relative./project/docs/readme.md
./project/src/app.ps1
./project/src/lib/util.ps1
./project/tests/app.Tests.ps1
./project/build/app.dll
./project/build/obj/app.pdb
--- -Depth 1:
./project/build
./project/docs
./project/src
./project/tests
./project/docs/readme.md
./project/src/lib
./project/src/app.ps1
./project/tests/app.Tests.ps1
./project/build/obj
./project/build/app.dll
--- skipping build output:
./project/docs/readme.md
./project/src/app.ps1
./project/src/lib/util.ps1
./project/tests/app.Tests.ps1-Exclude only looks at each item's own name, so it can't prune a whole subtree. Excluding
a folder like build and everything under it needs a Where-Object on FullName. The
[\\/] in the regex matches either path separator, so the same line works on Windows.
Testing paths with Test-Path
Test-Path returns $true or $false. It never throws for a missing path, which makes it the
right tool for if statements:
Test-Path -Path ./downloads/notes.txt
Test-Path -Path ./downloads/notes.txt -PathType Container
Test-Path -Path ./downloads -PathType Container
Test-Path -Path ./downloads/*.pdf
Test-Path -Path './downloads/report[final].txt'
Test-Path -LiteralPath './downloads/report[final].txt'
Test-Path -Path ./logs/app-2026-09-20.log -OlderThan (Get-Date).AddDays(-30)True
False
True
True
False
True
TrueLine by line: the file exists; it's not a folder; downloads is a folder; at least one
PDF exists (wildcards work); and then the trap. report[final].txt exists, but -Path
treats [final] as a wildcard character class (one of f, i, n, a, l), so it
looked for names like reportf.txt and found none. -LiteralPath takes the name as
written. Any script that handles user-supplied or downloaded file names should use
-LiteralPath. -OlderThan and -NewerThan compare LastWriteTime for you.
Creating files and folders with New-Item
New-Item -ItemType Directory -Path ./reports/2026/11 | Select-Object -Property Name, Parent
New-Item -ItemType Directory -Path ./reports/2026/11 -Force | Out-Null
'directory -Force on an existing folder: no error, contents untouched'
Set-Content -Path ./reports/summary.txt -Value 'total requests: 104,233'
"before: $((Get-Item -Path ./reports/summary.txt).Length) bytes"
New-Item -ItemType File -Path ./reports/summary.txt
New-Item -ItemType File -Path ./reports/summary.txt -Force | Out-Null
"after -Force: $((Get-Item -Path ./reports/summary.txt).Length) bytes"Name Parent
---- ------
11 /home/sid/files/reports/2026
directory -Force on an existing folder: no error, contents untouched
before: 24 bytes
New-Item: /home/sid/files/new-item.ps1:7
Line |
7 | New-Item -ItemType File -Path ./reports/summary.txt
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The file '/home/sid/files/reports/summary.txt'
| already exists.
after -Force: 0 bytesThree things to take from this:
New-Item -ItemType Directorycreates missing parent folders (2026here) on its own.-Forceon a directory is safe and idempotent: "make sure it exists".-Forceon a file that exists empties it. The 24-byte report became 0 bytes, without a warning. To "make sure a file exists" without destroying it, test first:if (-not (Test-Path $f)) { New-Item $f }.
Copying, moving, renaming and deleting
All four cmdlets support -WhatIf and -Confirm. Use -WhatIf the first time you run
anything that touches more than one file.
Copy-Item and the nested-folder surprise
Copy-Item -Path ./project -Destination ./project-backup -Recurse
(Get-ChildItem -Path ./project-backup -Directory).Name -join ', '
Copy-Item -Path ./project -Destination ./project-backup -Recurse
(Get-ChildItem -Path ./project-backup -Directory).Name -join ', 'build, docs, src, tests
build, docs, project, src, testsThe first copy created project-backup as a copy of project. The second time,
project-backup already existed, so Copy-Item copied project into it, and you now have
project-backup/project/.... A scheduled "backup" written this way nests one level deeper
on every run after the first. Copy the contents into a folder that you make sure exists:
Remove-Item -Path ./project-backup -Recurse -Force -ErrorAction Ignore
New-Item -ItemType Directory -Path ./project-backup | Out-Null
Copy-Item -Path ./project/* -Destination ./project-backup -Recurse -Force
Copy-Item -Path ./project/* -Destination ./project-backup -Recurse -Force
(Get-ChildItem -Path ./project-backup -Directory).Name -join ', 'build, docs, src, testsSame result no matter how many times it runs. -Force lets the copy overwrite files that
already exist in the destination.
Move-Item to a folder that doesn't exist
Copy-Item -Path ./downloads/notes.txt -Destination ./notes-copy.txt
Move-Item -Path ./notes-copy.txt -Destination ./sorted
Get-Item -Path ./sorted | Select-Object -Property Name, PSIsContainer, Length
Remove-Item -Path ./sortedName PSIsContainer Length
---- ------------- ------
sorted False 65There was no sorted folder, so Move-Item renamed the file to sorted. Move a whole
batch this way and each file overwrites the previous one. Create the destination folder
first, or end the destination with a separator and check with Test-Path -PathType Container.
Renaming in bulk
Rename-Item accepts a script block for -NewName, evaluated per file. -WhatIf shows
the plan, and -PassThru outputs the renamed items:
Get-ChildItem -Path ./downloads -Filter *.jpeg |
Rename-Item -NewName { $_.BaseName + '.jpg' } -WhatIf
Get-ChildItem -Path ./downloads -Filter *.jpeg |
Rename-Item -NewName { $_.BaseName + '.jpg' } -PassThru |
Select-Object -Property NameWhat if: Performing the operation "Rename File" on target "Item: /home/sid/files/downloads/IMG_2041.jpeg Destination: /home/sid/files/downloads/IMG_2041.jpg".
What if: Performing the operation "Rename File" on target "Item: /home/sid/files/downloads/IMG_2042.jpeg Destination: /home/sid/files/downloads/IMG_2042.jpg".
Name
----
IMG_2041.jpg
IMG_2042.jpgRemove-Item
Remove-Item -Path ./project-backup -Recurse -WhatIf
'---'
Get-ChildItem -Path ./downloads -File |
Where-Object LastWriteTime -lt (Get-Date).AddDays(-120) |
Remove-Item -WhatIfWhat if: Performing the operation "Remove Directory" on target "/home/sid/files/project-backup".
---
What if: Performing the operation "Remove File" on target "/home/sid/files/downloads/podcast-ep12.mp3".
What if: Performing the operation "Remove File" on target "/home/sid/files/downloads/setup-tool.zip".Deleting a non-empty folder without -Recurse asks for confirmation. In an unattended
script started with -NonInteractive, that prompt becomes an error, which is a good thing:
Remove-Item: /home/sid/files/remove-norecurse.ps1:1
Line |
1 | Remove-Item -Path ./project-backup
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| PowerShell is in NonInteractive mode. Read and Prompt functionality is
| not available.Hidden and read-only files need -Force. There is no recycle bin: Remove-Item deletes
for good.
Reading files with Get-Content
Get-Content returns an array of lines by default, which is what you want for
line-by-line work. -Raw returns the whole file as one string, which is what you want
for regex across lines or for passing to ConvertFrom-Json:
$lines = Get-Content -Path ./logs/app.log
'{0} lines, type {1}' -f $lines.Count, $lines.GetType().Name
$raw = Get-Content -Path ./logs/app.log -Raw
'{0} characters, type {1}' -f $raw.Length, $raw.GetType().Name
'--- -TotalCount 2:'
Get-Content -Path ./logs/app.log -TotalCount 2
'--- -Tail 2:'
Get-Content -Path ./logs/app.log -Tail 2
'--- line 7 (arrays are zero-based):'
$lines[6]12 lines, type Object[]
637 characters, type String
--- -TotalCount 2:
2026-11-10T00:01:00Z INFO request id=4001 status=200
2026-11-10T00:02:00Z INFO request id=4002 status=200
--- -Tail 2:
2026-11-10T00:11:00Z INFO request id=4011 status=200
2026-11-10T00:12:00Z INFO request id=4012 status=200
--- line 7 (arrays are zero-based):
2026-11-10T00:07:00Z ERROR request id=4007 status=503-TotalCount (alias -Head) stops reading after N lines, so it's instant even on a huge
file. -Tail reads from the end.
Following a growing log with -Wait
-Wait keeps the file open and outputs new lines as they're written, like tail -f.
Combined with Select-Object -First, it becomes "wait until this appears". Here another
process appended a line to live.log every second:
$started = Get-Date
Get-Content -Path ./logs/live.log -Wait -Tail 0 |
Where-Object { $_ -match ' ERROR ' } |
Select-Object -First 1
'stopped waiting after {0:N1}s' -f ((Get-Date) - $started).TotalSeconds2026-11-10T01:30:03Z ERROR request id=5003 status=503
stopped waiting after 2.3s-Tail 0 skips what was already in the file. Select-Object -First 1 stops the whole
pipeline, including the waiting Get-Content, as soon as the first match arrives. Without
it, -Wait runs until you press Ctrl+C. In a script, add your own deadline, as in the
polling loops from the loops article.
Reading big files quickly
Piping Get-Content line by line is convenient but slow, because every line becomes an
object and goes through the pipeline separately. On a 200,000-line log (in memory again,
to measure PowerShell rather than the disk):
$big = '/dev/shm/ps-c/big.log'
'{0:N1} MB' -f ((Get-Item -Path $big).Length / 1MB)
$t1 = Measure-Command { $n = 0; Get-Content -Path $big | ForEach-Object { $n++ } }
$t2 = Measure-Command { $n = 0; foreach ($batch in Get-Content -Path $big -ReadCount 5000) { $n += $batch.Count } }
$t3 = Measure-Command { $n = 0; switch -File $big { default { $n++ } } }
$t4 = Measure-Command { $n = 0; foreach ($line in [System.IO.File]::ReadLines($big)) { $n++ } }
'Get-Content | ForEach-Object {0,6:N0} ms' -f $t1.TotalMilliseconds
'Get-Content -ReadCount 5000 {0,6:N0} ms' -f $t2.TotalMilliseconds
'switch -File {0,6:N0} ms' -f $t3.TotalMilliseconds
'[IO.File]::ReadLines() {0,6:N0} ms' -f $t4.TotalMilliseconds11.6 MB
Get-Content | ForEach-Object 2,688 ms
Get-Content -ReadCount 5000 86 ms
switch -File 83 ms
[IO.File]::ReadLines() 108 msThirty times faster for the same work. -ReadCount 5000 sends lines in batches of 5,000,
switch -File reads and matches in one construct, and ReadLines streams lines straight
from .NET. All three keep memory flat. [System.IO.File] methods need a full path (see
the .NET current-directory trap below), which is why this example uses an absolute one.
Writing files: Set-Content, Add-Content, Out-File
Set-Contentreplaces a file's contents.Add-Contentappends. Both write each object's string value.Out-File(and the>and>>operators) write what you'd see on screen, formatted tables included.
New-Item -ItemType Directory -Path ./out -Force | Out-Null
Set-Content -Path ./out/hosts.txt -Value 'web01', 'web02'
Add-Content -Path ./out/hosts.txt -Value 'db01'
Get-Content -Path ./out/hosts.txt
'---'
$files = Get-ChildItem -Path ./downloads -Filter *.pdf | Select-Object -Property Name, Length
$files | Set-Content -Path ./out/set-content.txt
$files | Out-File -FilePath ./out/out-file.txt
Get-Content -Path ./out/set-content.txt
'---'
Get-Content -Path ./out/out-file.txtweb01
web02
db01
---
@{Name=invoice-2026-10.pdf; Length=250880}
@{Name=invoice-2026-11.pdf; Length=257024}
---
Name Length
---- ------
invoice-2026-10.pdf 250880
invoice-2026-11.pdf 257024
Neither is what you want for data. @{Name=…} is the object's ToString(), and the table
is console formatting, truncated to the console width. Write text with Set-Content, and
write structured data with Export-Csv or ConvertTo-Json, covered in
CSV, JSON, and XML. Use Out-File only when you
literally want a copy of what the screen showed.
Encoding: the big difference between 5.1 and 7
PowerShell 7 writes UTF-8 without a BOM everywhere by default. Windows PowerShell 5.1 used a different default for almost every cmdlet. Here is the same word written five ways in PowerShell 7.6.9, with the file bytes in hex:
New-Item -ItemType Directory -Path ./enc -Force | Out-Null
'café' | Set-Content -Path ./enc/set-content.txt
'café' | Out-File -FilePath ./enc/out-file.txt
'café' > ./enc/redirect.txt
'café' | Set-Content -Path ./enc/utf8bom.txt -Encoding utf8BOM
'café' | Set-Content -Path ./enc/unicode.txt -Encoding unicode
foreach ($file in Get-ChildItem -Path ./enc) {
$bytes = [System.IO.File]::ReadAllBytes($file.FullName)
'{0,-16} {1}' -f $file.Name, (($bytes | ForEach-Object { $_.ToString('X2') }) -join ' ')
}out-file.txt 63 61 66 C3 A9 0A
redirect.txt 63 61 66 C3 A9 0A
set-content.txt 63 61 66 C3 A9 0A
unicode.txt FF FE 63 00 61 00 66 00 E9 00 0A 00
utf8bom.txt EF BB BF 63 61 66 C3 A9 0Aé is C3 A9 in UTF-8. EF BB BF is the UTF-8 byte order mark (BOM), and FF FE marks
UTF-16LE, which PowerShell calls "Unicode". In Windows PowerShell 5.1 I ran the equivalent
(Out-File, Set-Content, Set-Content -Encoding UTF8, and >) in a script saved as
UTF-8 with a BOM:
outfile.txt FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00
setcontent.txt 63 61 66 E9 0D 0A
utf8.txt EF BB BF 63 61 66 C3 A9 0D 0A
redirect.txt FF FE 63 00 61 00 66 00 E9 00 0D 00 0A 00| Command | Windows PowerShell 5.1 | PowerShell 7 |
|---|---|---|
Out-File, >, >> | UTF-16LE with BOM | UTF-8, no BOM |
Set-Content, Add-Content | ANSI code page (E9 for é) | UTF-8, no BOM |
-Encoding UTF8 | UTF-8 with BOM | UTF-8, no BOM (utf8BOM adds one) |
| Line endings | CRLF (0D 0A) | The platform's: LF on Linux/macOS, CRLF on Windows |
Practical consequences:
- A 5.1 script that does
"..." > config.ymlproduces a UTF-16 file that most Linux tools, YAML parsers and git diffs can't read. UseSet-Content -Encoding utf8, or move the script to 7. - Reading has the same problem in reverse. 5.1's
Get-Contentassumes ANSI when a file has no BOM. For a UTF-8 file containingcaféwith no BOM, 5.1 printedcafé, and printedcaféonce I added-Encoding UTF8. - Scripts themselves are files too. My first 5.1 test script was saved as UTF-8
without a BOM, and 5.1 read the
'café'literal in its own source ascafé. The "UTF8" output file then containedC3 83 C2 A9, which is mojibake encoded again. Save.ps1files containing non-ASCII characters as UTF-8 with BOM if 5.1 has to run them. PowerShell 7 reads either.
Paths: Join-Path, Split-Path, Resolve-Path
Build paths with cmdlets instead of string concatenation. Then separators are always right
on every OS, and you never get // or a missing /:
Join-Path -Path /var/log -ChildPath app -AdditionalChildPath 2026, 'app.log'
$p = '/var/log/app/2026/app-2026-11-09.log.gz'
Split-Path -Path $p -Parent
Split-Path -Path $p -Leaf
Split-Path -Path $p -LeafBase
Split-Path -Path $p -Extension
[System.IO.Path]::ChangeExtension($p, '.txt')
'---'
Resolve-Path -Path ./downloads/*.pdf -Relative
(Resolve-Path -Path ./downloads/notes.txt).Path/var/log/app/2026/app.log
/var/log/app/2026
app-2026-11-09.log.gz
app-2026-11-09.log
.gz
/var/log/app/2026/app-2026-11-09.log.txt
---
./downloads/invoice-2026-10.pdf
./downloads/invoice-2026-11.pdf
/home/sid/files/downloads/notes.txt-AdditionalChildPath, -LeafBase and -Extension are PowerShell 6+ additions. In 5.1,
use nested Join-Path calls and [System.IO.Path]::GetFileNameWithoutExtension() /
GetExtension(). Note that "extension" means only the last one: .gz, not .log.gz.
The .NET current-directory trap
Set-Location changes PowerShell's location, but not the process's current directory,
which is what .NET methods use for relative paths:
Set-Location -Path ./downloads
"PowerShell location: $((Get-Location).Path)"
".NET current dir: $([System.Environment]::CurrentDirectory)"
[System.IO.File]::Exists('notes.txt')
Test-Path -Path notes.txt
[System.IO.File]::Exists((Join-Path -Path $PWD -ChildPath 'notes.txt'))PowerShell location: /home/sid/files/downloads
.NET current dir: /home/sid/files
False
True
TrueThe same thing happened in Windows PowerShell 5.1: after Set-Location into a subfolder,
[System.Environment]::CurrentDirectory still pointed at the starting folder, and
[System.IO.File]::Exists('notes.txt') returned False. Whenever you call
[System.IO.File], [System.IO.Directory] or a .NET constructor that takes a path, pass it
a full path from Resolve-Path, Join-Path $PWD, or an item's .FullName.
Attributes and timestamps
$file = Get-Item -Path ./downloads/invoice-2026-10.pdf
$file | Format-List -Property Name, Length, CreationTime, LastWriteTime, LastAccessTime, Attributes, UnixMode
$file.LastWriteTime = [datetime]'2026-06-30 17:45'
"LastWriteTime now: $((Get-Item -Path ./downloads/invoice-2026-10.pdf).LastWriteTime)"
$file.IsReadOnly = $true
"read-only: $((Get-Item -Path ./downloads/invoice-2026-10.pdf).UnixMode)"
$file.IsReadOnly = $false
"writable: $((Get-Item -Path ./downloads/invoice-2026-10.pdf).UnixMode)"
"hidden file attributes: $((Get-Item -Path ./downloads/.hidden-config -Force).Attributes)"Name : invoice-2026-10.pdf
Length : 250880
CreationTime : 10/03/2026 09:12:00
LastWriteTime : 10/03/2026 09:12:00
LastAccessTime : 10/03/2026 09:12:00
Attributes : Normal
UnixMode : -rw-r--r--
LastWriteTime now: 06/30/2026 17:45:00
read-only: -r--r--r--
writable: -rw-r--r--
hidden file attributes: HiddenLastWriteTimeis the timestamp to use for age-based cleanup. It's writable, which is also how you create realistic test data for a cleanup script.CreationTimeis meaningful on Windows. On Linux it isn't reliable. Here it simply matched the modification time I'd set when creating the test file.IsReadOnlymaps to the ReadOnly attribute on Windows and to the write permission bits on Linux.
On Windows, attributes are flags you combine with -bor. In Windows PowerShell 5.1, in my
scratch folder, marking a file Hidden made Get-ChildItem skip it until -Force was added:
$file = Get-Item -Path ./attr/settings.ini
$file.Attributes = $file.Attributes -bor [System.IO.FileAttributes]::Hidden
(Get-Item -Path ./attr/settings.ini -Force).Attributes
"without -Force: $((Get-ChildItem -Path ./attr).Name -join ', ')"
"with -Force: $((Get-ChildItem -Path ./attr -Force).Name -join ', ')"Hidden, Archive
without -Force: report.txt
with -Force: report.txt, settings.iniSizes: finding big and old files
Length is in bytes. Measure-Object -Sum adds it up, and PowerShell's KB, MB and GB
literals make conversion readable:
Get-ChildItem -Path ./downloads -File -Recurse |
Sort-Object -Property Length -Descending |
Select-Object -First 5 -Property Name, @{ Name = 'SizeMB'; Expression = { [math]::Round($_.Length / 1MB, 1) } }
$total = (Get-ChildItem -Path ./downloads -File -Recurse | Measure-Object -Property Length -Sum).Sum
'Total: {0:N1} MB' -f ($total / 1MB)Name SizeMB
---- ------
archive-2025.tar.gz 120.00
setup-tool.zip 48.00
podcast-ep12.mp3 7.20
holiday-photo.jpg 3.10
IMG_2042.jpeg 2.80
Total: 184.9 MBGrouping by extension shows where the space goes:
Get-ChildItem -Path ./downloads -File -Recurse |
Group-Object -Property Extension |
ForEach-Object {
[pscustomobject]@{
Extension = $_.Name
Files = $_.Count
SizeMB = [math]::Round(($_.Group | Measure-Object -Property Length -Sum).Sum / 1MB, 1)
}
} |
Sort-Object -Property SizeMB -Descending |
Format-Table -AutoSizeExtension Files SizeMB
--------- ----- ------
.gz 1 120.00
.zip 1 48.00
.mp3 1 7.20
.jpeg 2 5.60
.jpg 1 3.10
.pdf 2 0.50
.png 1 0.40
.xlsx 1 0.10
1 0.00
.docx 1 0.00
.txt 3 0.00The row with a blank extension is SHA256SUMS, which has none. Old files are a
Where-Object on LastWriteTime:
$cutoff = (Get-Date).AddDays(-30)
"cutoff: $($cutoff.ToString('yyyy-MM-dd HH:mm'))"
Get-ChildItem -Path ./logs -Filter 'app-*.log' |
Where-Object LastWriteTime -lt $cutoff |
Select-Object -Property Name, LastWriteTimecutoff: 2026-10-11 01:29
Name LastWriteTime
---- -------------
app-2026-09-20.log 09/20/2026 23:59:00
app-2026-09-23.log 09/23/2026 23:59:00
app-2026-09-26.log 09/26/2026 23:59:00
app-2026-09-29.log 09/29/2026 23:59:00
app-2026-10-02.log 10/02/2026 23:59:00
app-2026-10-05.log 10/05/2026 23:59:00
app-2026-10-08.log 10/08/2026 23:59:00Zip archives: Compress-Archive and Expand-Archive
New-Item -ItemType Directory -Path ./archive -Force | Out-Null
$october = Get-ChildItem -Path ./logs -Filter 'app-2026-10-*.log'
Compress-Archive -Path $october.FullName -DestinationPath ./archive/app-2026-10.zip
'{0}: {1:N0} bytes' -f 'app-2026-10.zip', (Get-Item -Path ./archive/app-2026-10.zip).Length
$zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path -Path ./archive/app-2026-10.zip).Path)
$zip.Entries | Select-Object -First 3 -Property FullName, Length, CompressedLength | Format-Table
"entries: $($zip.Entries.Count)"
$zip.Dispose()app-2026-10.zip: 2,052 bytes
FullName Length CompressedLength
-------- ------ ----------------
app-2026-10-02.log 125 91
app-2026-10-05.log 125 91
app-2026-10-08.log 125 91
entries: 10There's no cmdlet for listing a zip's contents, but the .NET ZipFile class is available in
PowerShell 7. Always Dispose() it, or the zip stays locked. Running the same
Compress-Archive again with a different file fails rather than silently replacing the
archive:
Compress-Archive: /home/sid/files/archive-exists.ps1:1
Line |
1 | Compress-Archive -Path ./logs/app-2026-11-01.log -DestinationPath ./a …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The archive file
| /home/sid/files/archive/app-2026-10.zip already
| exists. Use the -Update parameter to update the existing archive file or
| use the -Force parameter to overwrite the existing archive file.-Update adds or replaces entries in an existing archive, and -Force replaces the whole
archive. Expand-Archive restores:
Compress-Archive -Path ./logs/app-2026-11-01.log -DestinationPath ./archive/app-2026-10.zip -Update
Expand-Archive -Path ./archive/app-2026-10.zip -DestinationPath ./restored
(Get-ChildItem -Path ./restored).Count11Whether the archive contains the folder or just its contents depends on the path you
give it, exactly like Copy-Item:
Compress-Archive -Path ./project -DestinationPath ./archive/project.zip
Compress-Archive -Path ./project/* -DestinationPath ./archive/project-contents.zip
foreach ($name in 'project.zip', 'project-contents.zip') {
$zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path -Path "./archive/$name").Path)
"{0}: {1}" -f $name, (($zip.Entries.FullName | Select-Object -First 3) -join ', ')
$zip.Dispose()
}project.zip: project/docs/readme.md, project/src/app.ps1, project/src/lib/util.ps1
project-contents.zip: build/app.dll, build/obj/app.pdb, docs/readme.mdCompress-Archive is fine for logs and deployment bundles. For multi-gigabyte backups, use a
dedicated tool (tar, 7z, or the ZipFile .NET API directly), which is faster and gives
you more control.
File hashes with Get-FileHash
A hash identifies a file's exact contents. Use it to verify downloads, detect changes, and find duplicates. SHA256 is the default:
Get-FileHash -Path ./downloads/notes.txt | Format-List
Get-FileHash -Path ./downloads/notes.txt -Algorithm MD5 | Select-Object -Property Algorithm, HashAlgorithm : SHA256
Hash : 51EA96C3C4242E58C95A435DD8F62BDC79BDF520F9A9824526B1E1CBAD507BCD
Path : /home/sid/files/downloads/notes.txt
Algorithm Hash
--------- ----
MD5 58E951E95B0A7E5A1F9EF4812F10A2E5Verifying a download against a published checksum file, in the sha256sum format that most
projects publish:
Get-Content -Path ./downloads/SHA256SUMS
$expected = ((Get-Content -Path ./downloads/SHA256SUMS) -split '\s+')[0]
$actual = (Get-FileHash -Path ./downloads/setup-tool.zip -Algorithm SHA256).Hash
if ($actual -eq $expected) { 'checksum OK' } else { "checksum MISMATCH: $actual" }152ba99dbaf6c7dde5955a8484835194ed4fc0f20a0ea774667f148a25cb03c4 setup-tool.zip
checksum OKThe published hash is lower-case and Get-FileHash returns upper-case. -eq on strings is
case-insensitive in PowerShell, so the comparison still works. In C#, or with -ceq, it
wouldn't. Finding duplicates is cheap if you only hash files whose sizes match:
Get-ChildItem -Path ./downloads -File -Recurse |
Group-Object -Property Length |
Where-Object Count -gt 1 |
ForEach-Object { $_.Group | Get-FileHash } |
Group-Object -Property Hash |
Where-Object Count -gt 1 |
ForEach-Object { $_.Group.Path | Resolve-Path -Relative }./downloads/notes.txt
./downloads/old/notes (copy).txtWatching a folder with FileSystemWatcher
For drop folders ("process every CSV that lands in inbox"), .NET's FileSystemWatcher
reports changes as they happen, without polling. The simplest form is a loop around
WaitForChanged() with a timeout. A separate process created two CSV files and one text
file while this ran:
$inbox = (Resolve-Path -Path ./inbox).Path
$watcher = [System.IO.FileSystemWatcher]::new($inbox, '*.csv')
$until = (Get-Date).AddSeconds(7)
'watching {0} for *.csv until {1:HH:mm:ss}' -f (Split-Path -Path $inbox -Leaf), $until
while ((Get-Date) -lt $until) {
$change = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::Created, 1000)
if ($change.TimedOut) { continue }
'{0:HH:mm:ss} new file: {1}' -f (Get-Date), $change.Name
}
$watcher.Dispose()
'done'watching inbox for *.csv until 01:29:03
01:28:57 new file: orders-0931.csv
01:28:59 new file: orders-0932.csv
doneREADME.txt didn't match the *.csv filter, so it never appeared. Note the full path
passed to the constructor, because of the .NET current-directory trap. Two cautions:
"Created" fires when the file appears, which may be before the writer has finished. Real
drop-folder scripts wait until the file can be opened exclusively, or until its size stops
changing. And a watcher only sees events while it's running, so also sweep the folder at
startup for files that arrived while it was down. For long-running services,
Register-ObjectEvent hooks the watcher's events instead of looping. That pattern belongs
with background jobs.
Where you'll use this
- Log rotation and disk cleanup on servers where the application doesn't rotate its own logs, or where an agent fills a disk.
- Drop folders and integrations: a partner uploads CSVs over SFTP, a watcher or scheduled
sweep picks them up, processes them, and moves them to
processed/orfailed/. - Build and release tooling: copying artifacts, zipping a release, writing a
SHA256SUMSfile next to it. - Workstation housekeeping: sorting a Downloads folder, finding the space hogs, removing duplicates.
Here are two of those as complete scripts.
Log rotation with a dry run
This script compresses logs older than 7 days into one zip per month, verifies the zip
contains every file before deleting the originals, and deletes archives older than 90
days. SupportsShouldProcess gives it -WhatIf:
[CmdletBinding(SupportsShouldProcess)]
param(
[string]$LogPath = './logs',
[string]$ArchivePath = './archive',
[ValidateRange(1, 365)]
[int]$CompressAfterDays = 7,
[ValidateRange(1, 3650)]
[int]$DeleteArchivesAfterDays = 90
)
$ErrorActionPreference = 'Stop'
$now = Get-Date
if (-not (Test-Path -Path $ArchivePath)) {
$null = New-Item -ItemType Directory -Path $ArchivePath
}
# 1. Compress logs older than N days into one zip per month, then delete the originals.
$oldLogs = Get-ChildItem -Path $LogPath -Filter 'app-*.log' -File |
Where-Object LastWriteTime -lt $now.AddDays(-$CompressAfterDays)
foreach ($month in $oldLogs | Group-Object -Property { $_.LastWriteTime.ToString('yyyy-MM') }) {
$zipPath = Join-Path -Path $ArchivePath -ChildPath "app-$($month.Name).zip"
if ($PSCmdlet.ShouldProcess($zipPath, "Archive $($month.Count) log file(s)")) {
Compress-Archive -Path $month.Group.FullName -DestinationPath $zipPath -Update
# Verify before deleting anything: every file must now be inside the zip.
$zip = [System.IO.Compression.ZipFile]::OpenRead((Resolve-Path -Path $zipPath).Path)
try { $inZip = $zip.Entries.Name } finally { $zip.Dispose() }
$missing = $month.Group.Name | Where-Object { $_ -notin $inZip }
if ($missing) { throw "Not found in $zipPath after compressing: $($missing -join ', ')" }
$month.Group | Remove-Item
[pscustomobject]@{ Action = 'Archived'; Target = Split-Path -Path $zipPath -Leaf; Files = $month.Count }
}
}
# 2. Delete archives older than the retention period.
Get-ChildItem -Path $ArchivePath -Filter 'app-*.zip' -File |
Where-Object LastWriteTime -lt $now.AddDays(-$DeleteArchivesAfterDays) |
ForEach-Object {
if ($PSCmdlet.ShouldProcess($_.Name, 'Delete expired archive')) {
Remove-Item -LiteralPath $_.FullName
[pscustomobject]@{ Action = 'Deleted'; Target = $_.Name; Files = 1 }
}
}The test folder had 17 daily logs from 2026-09-20 to 2026-11-07 plus the current
app.log, and an old app-2026-06.zip dated 1 July:
(Get-ChildItem -Path ./logs -Filter 'app-*.log').Count
(Get-ChildItem -Path ./archive).Name
./Invoke-LogRotation.ps1 -WhatIf
'--- real run:'
./Invoke-LogRotation.ps1 | Format-Table
'--- second run:'
./Invoke-LogRotation.ps1 | Format-Table
'--- what is left:'
(Get-ChildItem -Path ./logs).Name -join ', '
(Get-ChildItem -Path ./archive).Name -join ', '17
app-2026-06.zip
What if: Performing the operation "Archive 4 log file(s)" on target "./archive/app-2026-09.zip".
What if: Performing the operation "Archive 10 log file(s)" on target "./archive/app-2026-10.zip".
What if: Performing the operation "Archive 1 log file(s)" on target "./archive/app-2026-11.zip".
What if: Performing the operation "Delete expired archive" on target "app-2026-06.zip".
--- real run:
Action Target Files
------ ------ -----
Archived app-2026-09.zip 4
Archived app-2026-10.zip 10
Archived app-2026-11.zip 1
Deleted app-2026-06.zip 1
--- second run:
--- what is left:
app-2026-11-04.log, app-2026-11-07.log, app.log
app-2026-09.zip, app-2026-10.zip, app-2026-11.zipThe two most recent daily logs and the live app.log were left alone, and the second run had
nothing to do. Scheduled daily with pwsh -NonInteractive -File, this keeps the disk in
check indefinitely. Because the zip check runs before Remove-Item, a full disk or a
permissions problem during compression stops the script with the originals intact.
Organising a downloads folder by type
This one moves each file into a category folder based on its extension. It never overwrites:
a name collision gets (1), (2) and so on. The category map is an [ordered]
hashtable, so the order is predictable:
[CmdletBinding(SupportsShouldProcess)]
param(
[string]$Path = './downloads',
[string]$Destination = './organized'
)
$categories = [ordered]@{
Documents = '.pdf', '.docx', '.xlsx', '.txt'
Images = '.jpg', '.jpeg', '.png'
Audio = '.mp3'
Archives = '.zip', '.gz'
}
foreach ($file in Get-ChildItem -Path $Path -File) {
$category = 'Other'
foreach ($entry in $categories.GetEnumerator()) {
if ($file.Extension -in $entry.Value) {
$category = $entry.Key
break
}
}
$folder = Join-Path -Path $Destination -ChildPath $category
$target = Join-Path -Path $folder -ChildPath $file.Name
$n = 1
while (Test-Path -LiteralPath $target) {
$target = Join-Path -Path $folder -ChildPath ('{0} ({1}){2}' -f $file.BaseName, $n++, $file.Extension)
}
if ($PSCmdlet.ShouldProcess($file.Name, "Move to $category/$(Split-Path -Path $target -Leaf)")) {
if (-not (Test-Path -Path $folder)) {
$null = New-Item -ItemType Directory -Path $folder
}
Move-Item -LiteralPath $file.FullName -Destination $target
[pscustomobject]@{ File = $file.Name; Category = $category; NewName = Split-Path -Path $target -Leaf }
}
}organized/Documents/notes.txt already existed before the run:
./Move-DownloadsByType.ps1 -WhatIf
'--- real run:'
$moved = ./Move-DownloadsByType.ps1
$moved | Group-Object -Property Category | Format-Table -Property Name, Count
'--- renamed to avoid overwriting:'
$moved | Where-Object { $_.File -ne $_.NewName } | Format-Table
'--- left in downloads:'
(Get-ChildItem -Path ./downloads -Force).Name -join ', 'What if: Performing the operation "Move to Images/holiday-photo.jpg" on target "holiday-photo.jpg".
What if: Performing the operation "Move to Images/IMG_2041.jpeg" on target "IMG_2041.jpeg".
What if: Performing the operation "Move to Images/IMG_2042.jpeg" on target "IMG_2042.jpeg".
What if: Performing the operation "Move to Documents/invoice-2026-10.pdf" on target "invoice-2026-10.pdf".
What if: Performing the operation "Move to Documents/invoice-2026-11.pdf" on target "invoice-2026-11.pdf".
What if: Performing the operation "Move to Documents/meeting-notes.docx" on target "meeting-notes.docx".
What if: Performing the operation "Move to Documents/notes (1).txt" on target "notes.txt".
What if: Performing the operation "Move to Audio/podcast-ep12.mp3" on target "podcast-ep12.mp3".
What if: Performing the operation "Move to Documents/report-q3.xlsx" on target "report-q3.xlsx".
What if: Performing the operation "Move to Documents/report[final].txt" on target "report[final].txt".
What if: Performing the operation "Move to Images/screenshot.png" on target "screenshot.png".
What if: Performing the operation "Move to Archives/setup-tool.zip" on target "setup-tool.zip".
What if: Performing the operation "Move to Other/SHA256SUMS" on target "SHA256SUMS".
--- real run:
Name Count
---- -----
Archives 1
Audio 1
Documents 6
Images 4
Other 1
--- renamed to avoid overwriting:
File Category NewName
---- -------- -------
notes.txt Documents notes (1).txt
--- left in downloads:
old, .hidden-configreport[final].txt moved correctly because the script uses -LiteralPath throughout. The
hidden .hidden-config and the old folder were left alone, because Get-ChildItem -File
without -Force skips hidden files, which is a sensible default for a tidy-up script.
Common mistakes
Square brackets in file names
Remove-Item -Path './downloads/report[final].txt'
"after -Path: exists = $(Test-Path -LiteralPath './downloads/report[final].txt')"
Remove-Item -LiteralPath './downloads/report[final].txt'
"after -LiteralPath: exists = $(Test-Path -LiteralPath './downloads/report[final].txt')"after -Path: exists = True
after -LiteralPath: exists = FalseNo error and no deletion. -Path treated [final] as a wildcard that matched nothing.
File names that come from downloads, exports and other people often contain square brackets.
Use -LiteralPath whenever the path comes from data rather than from you.
Hidden files are skipped, and can't be deleted, without -Force
Remove-Item -Path ./downloads/.hidden-config
"exists: $(Test-Path -Path ./downloads/.hidden-config)"
Remove-Item -Path ./downloads/.hidden-config -Force
"exists: $(Test-Path -Path ./downloads/.hidden-config)"Remove-Item: /home/sid/files/hidden-remove.ps1:1
Line |
1 | Remove-Item -Path ./downloads/.hidden-config
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| You do not have sufficient access rights to perform this operation or
| the item is hidden, system, or read only.
exists: True
exists: FalseThe message talks about access rights, but the cause is the hidden flag. On Linux that means any dot-file.
-Include returning nothing
Get-ChildItem -Path ./downloads -Include *.pdf returns nothing. Add -Recurse, use a
wildcard path (./downloads/*), or use -Filter for a single pattern.
Copy-Item nesting on the second run, and Move-Item renaming
Copy-Item -Recurse into an existing folder nests the source inside it. Move-Item to a
folder that doesn't exist renames the file. Copy source/* into a folder you've created, and
check destinations with Test-Path -PathType Container.
Relative paths with .NET methods
[System.IO.File]::ReadAllText('notes.txt') resolves against the process directory, not
your PowerShell location. Pass .FullName or a Resolve-Path result.
Summary
Get-ChildItemreturns objects. Use-File/-Directory,-Recurse/-Depth, and-Forcefor hidden items. Prefer-Filter(fast, one pattern).-Includeneeds-Recurseor a wildcard path, and on Windows-Filter *.htmalso matches.html.- Use
-LiteralPathfor any name that might contain[or]. With-Path, such names silently match nothing. New-Item -Forceis safe for directories but empties existing files.Copy-Item -Recurseinto an existing folder nests.Move-Itemto a missing folder renames. Preview everything with-WhatIf.Get-Contentgives lines.-Rawgives one string.-Tailand-Waitfollow logs. For big files,-ReadCount,switch -Fileor[IO.File]::ReadLines()are about 30 times faster than piping line by line.- PowerShell 7 writes UTF-8 without BOM everywhere. 5.1's
Out-File/>write UTF-16LE andSet-Contentwrites ANSI, so be explicit with-Encodingin scripts that must run on both. - Build paths with
Join-Path/Split-Path, and give .NET methods full paths, because they don't followSet-Location. LastWriteTimedrives age-based cleanup.Measure-Object -Sum LengthandGroup-Object Extensionfind where the space went.Get-FileHashverifies downloads and finds duplicates.Compress-Archiveneeds-Updateor-Forcefor an existing zip, andfoldervsfolder/*decides whether the top folder goes in. Verify an archive before deleting what you put in it.
Exercises
List every .log file in ./logs modified in the last 14 days, newest first, showing the
name, the last write time and the size in KB to two decimal places.
Show Solution
Get-ChildItem -Path ./logs -Filter *.log -File |
Where-Object LastWriteTime -gt (Get-Date).AddDays(-14) |
Sort-Object -Property LastWriteTime -Descending |
Select-Object -Property Name, LastWriteTime, @{ Name = 'SizeKB'; Expression = { [math]::Round($_.Length / 1KB, 2) } }Name LastWriteTime SizeKB
---- ------------- ------
app.log 11/10/2026 01:31:02 0.62
app-2026-11-07.log 11/07/2026 23:59:00 0.12
app-2026-11-04.log 11/04/2026 23:59:00 0.12
app-2026-11-01.log 11/01/2026 23:59:00 0.12
app-2026-10-29.log 10/29/2026 23:59:00 0.12-Filter does the cheap filtering at the file system level, and Where-Object handles the
date. The calculated property formats the size without changing the underlying object.
Count the files under ./downloads (including sub-folders) by extension, case-insensitively,
showing files with no extension as (none). Sort by count, highest first, then by extension.
Show Solution
Get-ChildItem -Path ./downloads -File -Recurse |
Group-Object -Property { if ($_.Extension) { $_.Extension.ToLower() } else { '(none)' } } |
Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name |
Select-Object -Property Name, CountName Count
---- -----
.txt 3
.jpeg 2
.pdf 2
.docx 1
.gz 1
.jpg 1
.mp3 1
.png 1
.xlsx 1
.zip 1
(none) 1Grouping by a script block lets you normalise the key. .JPG and .jpg would otherwise be
separate groups on Linux. The hashtable passed to Sort-Object gives the count its own sort
direction.
Write Get-FolderSize -Path <folder>, which outputs one object per immediate sub-folder with
its total size in MB, counting every file below it, hidden ones included. Show the four
largest sub-folders of the current directory.
Show Solution
function Get-FolderSize {
[CmdletBinding()]
param([string]$Path = '.')
foreach ($dir in Get-ChildItem -Path $Path -Directory) {
$sum = (Get-ChildItem -LiteralPath $dir.FullName -File -Recurse -Force -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum).Sum
[pscustomobject]@{
Folder = $dir.Name
SizeMB = [math]::Round([double]$sum / 1MB, 2)
}
}
}
Get-FolderSize -Path . | Sort-Object -Property SizeMB -Descending | Select-Object -First 4Folder SizeMB
------ ------
downloads 184.92
inbox 0.00
logs 0.00
project 0.00-ErrorAction SilentlyContinue keeps one unreadable folder (common under C:\Windows or
/proc) from flooding the output. [double]$sum handles empty folders, where Sum is
$null.
Write Sync-Folder -Source -Destination that copies files from the source tree to the
destination, preserving the folder structure, but only when the file is new or its size or
LastWriteTime differs. Support -WhatIf, and output one object per copied file with the
relative path and the reason (new or changed). Show a dry run, a first run, a second run
that copies nothing, and a run after editing one file.
Hint
[System.IO.Path]::GetRelativePath($root, $file.FullName) gives the path relative to the
source root. Copy-Item preserves LastWriteTime, which is what makes the second run a
no-op.
Show Solution
function Sync-Folder {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)][string]$Source,
[Parameter(Mandatory)][string]$Destination
)
$sourceRoot = (Resolve-Path -Path $Source).Path
foreach ($file in Get-ChildItem -Path $sourceRoot -File -Recurse) {
$relative = [System.IO.Path]::GetRelativePath($sourceRoot, $file.FullName)
$target = Join-Path -Path $Destination -ChildPath $relative
$existing = Get-Item -LiteralPath $target -ErrorAction Ignore
if ($existing -and $existing.Length -eq $file.Length -and $existing.LastWriteTime -eq $file.LastWriteTime) {
continue
}
$reason = if ($existing) { 'changed' } else { 'new' }
if ($PSCmdlet.ShouldProcess($relative, "Copy ($reason)")) {
$parent = Split-Path -Path $target -Parent
if (-not (Test-Path -Path $parent)) { $null = New-Item -ItemType Directory -Path $parent }
Copy-Item -LiteralPath $file.FullName -Destination $target
[pscustomobject]@{ File = $relative; Reason = $reason }
}
}
}Saved as Sync-Folder.ps1 and tested:
. ./Sync-Folder.ps1
Sync-Folder -Source ./project -Destination ./mirror -WhatIf
'--- first run:'
Sync-Folder -Source ./project -Destination ./mirror | Format-Table
'--- second run (nothing changed):'
@(Sync-Folder -Source ./project -Destination ./mirror).Count
'--- after editing one file:'
Add-Content -Path ./project/docs/readme.md -Value 'Run ./src/app.ps1 to start.'
Sync-Folder -Source ./project -Destination ./mirror | Format-TableWhat if: Performing the operation "Copy (new)" on target "docs/readme.md".
What if: Performing the operation "Copy (new)" on target "src/app.ps1".
What if: Performing the operation "Copy (new)" on target "src/lib/util.ps1".
What if: Performing the operation "Copy (new)" on target "tests/app.Tests.ps1".
What if: Performing the operation "Copy (new)" on target "build/app.dll".
What if: Performing the operation "Copy (new)" on target "build/obj/app.pdb".
--- first run:
File Reason
---- ------
docs/readme.md new
src/app.ps1 new
src/lib/util.ps1 new
tests/app.Tests.ps1 new
build/app.dll new
build/obj/app.pdb new
--- second run (nothing changed):
0
--- after editing one file:
File Reason
---- ------
docs/readme.md changedcontinue inside the foreach skips unchanged files cheaply, before any copy. return
would have ended the whole function. This is the core of what robocopy and rsync do. They
add deletion of files that vanished from the source, retries, and much better performance on
large trees.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1 on
Windows 11, November 2026. Every Linux example was run as shown with pwsh -NoProfile -File.
The large files were sparse files created with truncate, and the timing tests used a
3,000-file tree and a 200,000-line log in /dev/shm, deleted afterwards. The 5.1 results
(the -Filter 8.3 quirk, the encoding bytes, reading a BOM-less file, the .NET
current-directory check and the Hidden attribute) came from scripts that only touched files
in a scratch folder. For the FileSystemWatcher and -Wait examples, a short background
shell process created the inbox files and appended the log lines, then exited on its own. Paths from the test machine's scratch directories are shown shortened to /home/sid/….
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.