What would you like to learn?

Try PowerShell, networks, XSS, or Step 138

Browse the full curriculum →

PowerShell

Step 2. Working with Files — Create, Copy, Move, Delete

Step 2Estimated practice · 2–3 hours

Level 0 — Understanding How to Operate a Computer and How It’s Structured | Difficulty ★☆☆☆☆ | Estimated time: 2–3 hours

Prerequisites: Step 1 complete (opening PowerShell, pwd/ls/cd). We’ll continue in Windows PowerShell today.

  • What you need: a Windows PC, PowerShell.
  • Safety: every experiment today happens only inside a dedicated practice folder we’ll create at the start. Use only disposable files created in this lesson. A wrong location can affect other files, so check it with pwd before making changes.
  • Caution: watch for overwrites by Set-Content and Copy-Item, moves by Move-Item, and deletion by Remove-Item. Deletion in PowerShell does not go through the Recycle Bin. You cannot restore it through the Recycle Bin, and recovery without a separate backup is not guaranteed. So today we’ll work even harder on “how to delete safely” than on “how to delete.”

You can copy files with a mouse. But “pick out only the 300 .txt files in this folder and copy them” is easy to express as a repeatable command. “Move the logs to the backup folder every night” needs automation, and remote servers are often managed through a command line. In security work, file manipulation isn’t “tidying documents” — it’s handling evidence: today, we learn the basic operations using text files we create ourselves. Do not use real incident evidence or malware as practice material.


1. Learning Objectives

By the end of this unit, you can:

  • Create files and folders with New-Item
  • Write to and read from files with Set-Content / Get-Content
  • Distinguish and use Copy-Item (copy) vs Move-Item (move)
  • Select only matching files with wildcards (*) and work on them
  • Use the safety habit of previewing targets with -WhatIf before deleting

2. Background Knowledge — Today’s Tools and Concepts

This section’s Tools at a Glance

Category Details
Language/environment Windows PowerShell 5.1 or PowerShell 7, Windows file system. Use a normal non-administrator session.
This section’s commands New-Item (create), Set-Content/Add-Content/Get-Content (write/append/read), Copy-Item (copy), Move-Item (move), Remove-Item (delete)
This section’s options -WhatIf (preview), -Recurse (including children), -Exclude (exclude)
Concepts you need file extensions, wildcards (*, ?), “copy vs move,” what permanent deletion means

2-1. Extensions — A File’s Name Tag

The part after the last . in a filename is the extension — like .txt in report.txt or .exe in setup.exe. It suggests the intended file type. Renaming an extension does not convert the actual format, and an extension alone cannot establish that a file is safe.

Extension Type
.txt text document
.exe executable program
.ps1 PowerShell script
.zip compressed archive
.log log (record) file

One security note: depending on Explorer settings, known file extensions may be hidden. So a file that looks like invoice.pdf may actually be invoice.pdf.exe (an executable!) — a classic malware trap. Turning on “File name extensions” in Explorer settings is the easiest security upgrade a beginner can make. In the CLI, ls always shows extensions, so the habit forms naturally.

2-2. Wildcards — Symbols for “Any Characters”

* (asterisk) is a special symbol meaning “any number of any characters can go here.” Think of it as the joker in a deck of cards.

Pattern Meaning Matches
*.txt everything ending in .txt a.txt, diary.txt
log* everything starting with log log1.txt, logfile.zip
report?.txt report + one character + .txt report1.txt, reportA.txt

This symbol is this section’s key weapon. Conditional selection like “only the .txt files out of 300” is what it does.


3. Follow Along

Before you begin. Create the unique practice directory before making changes. Preview deletion, inspect the resolved target, and keep recovery copies. A successful command is not a backup.

3-1. Create a New Practice Folder

Create a unique folder on each run to keep this exercise separate from existing files. Enter the setup below in a normal PowerShell session. The long folder name is generated for you.

$practice = Join-Path $HOME ('infosec-step02-' + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $practice -ErrorAction Stop
Set-Location -LiteralPath $practice
pwd

$practice holds this practice folder’s full path. Join-Path combines path components; the GUID helps avoid name collisions. Directory means a folder and File a file. If a command fails, resolve the error before continuing.

Record the printed path. The variable disappears when you close the session. To resume later, check the recorded folder and assign that path to $practice again. Keep personal documents and downloaded files out of this practice folder.

3-2. Create, Overwrite, and Append

Create an empty file, write text, and read it back. Run each command and inspect its result.

New-Item -ItemType File test.txt
Set-Content test.txt "hello security" -Encoding UTF8
Get-Content test.txt -Encoding UTF8
hello security

Immediately after New-Item, the file is 0 bytes. Set-Content replaces its content. Compare replacing with appending:

Set-Content test.txt "second line" -Encoding UTF8
Get-Content test.txt -Encoding UTF8
Add-Content test.txt "third line" -Encoding UTF8
Get-Content test.txt -Encoding UTF8
second line
third line

The last read returns two lines. Explicit -Encoding UTF8 makes reading and writing non-ASCII text predictable. UTF8 in 5.1 includes a BOM; UTF8 in 7 normally does not. Identical text can therefore have different byte counts. Verify the contents instead of expecting an arbitrary size from a sample listing.

3-3. Copy — Check the Original and the Copy

Copy-Item test.txt backup.txt
Get-Content test.txt -Encoding UTF8
Get-Content backup.txt -Encoding UTF8
ls

Both test.txt and backup.txt must exist, with the same two lines. Check whether the destination name is already in use before copying. Copy-Item can overwrite an existing ordinary file.

Real evidence preservation also involves hashes, metadata, acquisition records, and appropriate collection tools. This basic text-copy exercise is not a complete forensic acquisition procedure.

3-4. Copy into an Existing Folder

New-Item -ItemType Directory backup
Copy-Item test.txt backup
ls backup

Because backup exists as a folder, the copy appears at .\backup\test.txt. If that folder does not exist, the same command can create a file named backup. Resolve a folder-creation error before continuing.

3-5. Move and Rename — Keep the Backslash

Move-Item test.txt .\backup\moved.txt
ls
ls backup

The original test.txt should no longer be in the current folder. Inside backup, you should see moved.txt and the test.txt copied earlier.

The \ in backup\moved.txt separates the folder from the filename. Without it, backupmoved.txt renames the file in the current folder. Verify both the source location and the destination after moving.

Move-Item backup.txt renamed.txt
ls

This renames backup.txt to renamed.txt in the same folder. If the destination already exists or the move fails, inspect the error and both locations instead of assuming success.

3-6. Inspect Wildcard Matches, Then Copy

New-Item -ItemType File a.txt, b.txt, c.txt, a.log, b.log
ls *.txt
Copy-Item *.txt backup
ls backup

At this point the current-folder matches are a.txt, b.txt, c.txt, and renamed.txt. The earlier moved.txt and test.txt remain in backup. A wildcard matches names, so real operations must also check that an unexpectedly matching directory has not entered the selection.

Next, copy names beginning with a. Creating backup2 below is a required exercise step.

New-Item -ItemType Directory backup2
ls a*
Copy-Item a* backup2
ls backup2

backup2 must contain a.log and a.txt. The next section deletes only this folder.

Note: the details of ? matching depend on the option and file system. On the tested system, ls report?.txt selected report1.txt and reportA.txt, while Get-ChildItem -Filter report?.txt also selected report.txt. Inspect the actual selection before acting.

3-7. Delete — Preview and Verify the Result

First check that pwd is the practice folder recorded in 3-1. Remove-Item does not send files to the Recycle Bin. -WhatIf previews a proposed operation; it is not a backup or an undo mechanism. -LiteralPath treats the path literally rather than interpreting characters such as * as wildcards.

pwd
Remove-Item -LiteralPath .\renamed.txt -WhatIf
ls renamed.txt

The file should still exist after the preview. Confirm that the only target is the renamed.txt created in this exercise before running:

Remove-Item -LiteralPath .\renamed.txt
ls

Now practice wildcard deletion using just two new disposable files:

New-Item -ItemType File victim1.txt, victim2.txt
ls .\victim*.txt
Remove-Item .\victim*.txt -WhatIf
ls .\victim*.txt

Both files must still exist. If the preview includes anything else, stop and narrow the pattern. The file list can change between preview and execution.

Remove-Item .\victim*.txt
ls .\victim*.txt

Only those two practice files should disappear, leaving an empty listing. Before deleting a directory, check its full path and every child item. The following guard requires the target to be backup2 immediately under the recorded practice folder:

$discard = (Resolve-Path -LiteralPath '.\backup2').Path
if ($discard -ne (Join-Path $practice 'backup2')) { throw 'Check the practice folder.' }
$discard
Get-ChildItem -LiteralPath $discard -Recurse
Remove-Item -LiteralPath $discard -Recurse -WhatIf

Confirm that backup2 contains only the a.txt and a.log copied in this lesson. Then run the line below. -Recurse includes all children; do not substitute personal files or another path.

Remove-Item -LiteralPath $discard -Recurse
ls

Verify that backup2 is gone. Keep the top-level practice folder and the remaining results.


4. Missions & Exercises

Mission — File Manager Exam

Return with Set-Location -LiteralPath $practice, then complete the mission below. If project already exists, inspect your earlier results before repeating anything.

  1. Create a folder called project and enter it.
  2. Inside, create four files: plan.txt, memo.txt, data.csv, run.log.
  3. Write “This is the plan.” into plan.txt, then read it back to confirm.
  4. Create an archive folder and copy only the .txt files into it. (The original plan.txt must remain.)
  5. Move run.log into the archive folder. (It must no longer be in the original location.)
  6. Simulate deleting data.csv with -WhatIf, then really delete it.
  7. Finally, verify that ls and ls archive look like this:
    • Current folder: plan.txt, memo.txt, archive
    • Inside archive: plan.txt, memo.txt, run.log

Exercises

Exercise 1. Explain the difference between Copy-Item and Move-Item in one sentence.

Exercise 2. The current folder contains a.txt, b.txt, and c.log. Instead of Copy-Item *.* backup, you want to copy everything except the .log files. Assume you have also created an empty backup folder and there are no other items. Write two ways to do it.

Exercise 3. You ran Remove-Item *.txt -WhatIf, and besides the files you meant to delete, notes.txt appeared in the list. What should you do?

Exercise 4. You ran Set-Content a.txt "first" -Encoding UTF8 and then Set-Content a.txt "second" -Encoding UTF8. What does a.txt contain now? If you wanted to append instead, which command would you use?


Answers & completion criteria · expand/collapse

5. Model Answers & Completion Criteria

Mission Walkthrough

This sequence is for the first mission run. Do not run it over an existing project created while solving the mission above.

Set-Location -LiteralPath $practice
New-Item -ItemType Directory project -ErrorAction Stop
cd project
New-Item -ItemType File plan.txt, memo.txt, data.csv, run.log
Set-Content plan.txt "This is the plan." -Encoding UTF8
Get-Content plan.txt -Encoding UTF8
New-Item -ItemType Directory archive
Copy-Item *.txt archive
Move-Item run.log .\archive\run.log
Remove-Item -LiteralPath .\data.csv -WhatIf

Confirm that the preview targets only project\data.csv, then finish:

Remove-Item -LiteralPath .\data.csv
ls
ls archive

Final state: the current folder contains archive, memo.txt, and plan.txt. Archive contains memo.txt, plan.txt, and run.log. Both plan.txt files must contain the same sentence, and data.csv must be absent.

Exercise Answers

Answer 1. Copy (Copy-Item) leaves the original in place; move (Move-Item) removes the original and carries it to the destination. (A Move-Item within the same folder becomes a “rename.”)

Answer 2.

  • Method 1 (wildcard): Copy-Item *.txt backup
  • Method 2 (exclude option): Copy-Item * backup -Exclude *.log,backup (also exclude the destination folder itself)

Answer 3. Don’t remove -WhatIf — stop. WhatIf shows the expected targets at that time; files can change later and an operation can still fail. Narrow the pattern (e.g., use only the common part of the filenames, like victim*.txt), check again with -WhatIf, and only run it for real when the list is exactly right. This is precisely why WhatIf exists.

Answer 4. The content is only second — Set-Content overwrites. To append, use Add-Content a.txt "second" -Encoding UTF8.

Completion Checklist

  • [ ] I can create both files and folders with New-Item
  • [ ] I can do the write-with-Set-Content, verify-with-Get-Content cycle
  • [ ] I can explain the difference between copy (Copy) and move (Move)
  • [ ] I can select and act on files with wildcards like *.txt
  • [ ] I’ve experienced the habit of previewing with -WhatIf before deleting
  • [ ] I produced the exact final state of mission steps 1–7

6. Common Pitfalls & Fixes

Wall 1. “I deleted an important file with Remove-Item!”

If you accidentally delete an important file, reduce further writes to that storage device and check available backups or snapshots first. Recovery is not guaranteed, so prevention comes first:

  1. Check the targets with ls before deleting
  2. When deleting with wildcards, always -WhatIf first
  3. For anything important, don’t delete — build a habit of moving it to a “trash folder” with Move-Item

Wall 2. I ran Copy-Item and got something unintended instead of a copy of the original

If you run Copy-Item a.txt backup when the destination folder doesn’t exist, PowerShell may interpret backup as a new filename rather than a folder. When copying into a folder, create the destination folder first (New-Item -ItemType Directory backup), and make it a set: copy, then verify with ls backup.

Wall 3. Spaces in the path break the command

Same rule as Step 1: wrap it in quotes, like Copy-Item "my file.txt" backup. Starting today, the habit of naming files/folders with - or _ instead of spaces also makes CLI life easier. (That’s why developers’ filenames are full of underscores.)

Wall 4. The wildcard selects more (or fewer) files than I expected

When you can’t be certain of the range * will catch, select first before deleting or overwriting: ls *.txt. Use the list to check the expected selection, but options and later changes can affect the actual operation. Verify the result afterward too. Drill the order “verify selection → act” into your body.

Wall 5. I moved something with Move-Item and panicked because the original was gone

It’s normal for a move to remove the original. If you wanted the original kept, that was a job for copy (Copy-Item). If you forgot where you moved it, don’t run ls all over the place — press ↑ to see the command you just typed. The destination is written right there.


7. Summary

Commands You Learned Today

Command What it does Example
New-Item Create a file/folder New-Item a.txt, New-Item -ItemType Directory dir
Set-Content Write content (overwrites) Set-Content a.txt "text" -Encoding UTF8
Add-Content Append content Add-Content a.txt "text" -Encoding UTF8
Get-Content Read content Get-Content a.txt -Encoding UTF8
Copy-Item Copy (original stays, overwrites same names) Copy-Item *.txt backup
Move-Item Move/rename (original disappears) Move-Item a.txt .\backup\b.txt
Remove-Item Delete (no Recycle Bin) Remove-Item *.log -WhatIf

Key Concepts

Concept One-line summary
Extension A tag for the file type. Always keep it visible
Wildcard * “Any characters” — the weapon of conditional selection
-WhatIf Pre-run simulation. The seatbelt of deletion
-Recurse The whole folder at once (including children)

Instincts That Matter More Than Commands

“Look before you delete, then delete after looking.” And “analyze the copy; preserve the original.” These two sentences go beyond file manipulation — they’re iron rules of incident response.

Deleting a file and securely sanitizing storage are different operations. Recovery depends on the device, TRIM, subsequent writes, and backups. Repeatedly overwriting a file is not a universal SSD sanitization method. This lesson does not perform recovery or storage sanitization.


Once every box is checked, Step 2 is complete.


Practice verification record

Historical record. The dated record below describes the earlier lesson version. The current instructions include subsequent editorial corrections; that record does not certify every revised example.

2026-09-10 · Checked 34 items in each environment: Windows 11 with Windows PowerShell 5.1.26100.9444 and PowerShell 7.6.5. Used newly created practice folders to verify overwrite, append, copy, move, wildcards, WhatIf, directory deletion, and the mission’s exact final file lists. Reproduced the original missing-backslash error, then verified the corrected destination and file contents. Real evidence acquisition, malware execution, and deleted-file recovery were outside this check.

References: Microsoft Remove-Item · Character encoding · Wildcards

ONE STEP FURTHER

Finished this lesson?

Check the completion criteria, then mark your progress.

Something wrong with this page or a link? Let us know.
Next