🗃️ PowerShell and file manipulation
- Solo, at your own pace
🎯 Learning Objective
- Manipulate files and directories via PowerShell
- Automate simple tasks with scripts
- Use relative and absolute paths
- Search for files and textual content in a directory tree
- Display and modify file permissions
📜 Statement
🔧 Context
A system administrator assigns you a series of tasks to perform via PowerShell. These tasks could be automated in a small script. You need to create a working environment, manipulate files and directories, all using PowerShell.
📁 Step 1 – Prepare an environment
- Open PowerShell in a working folder of your choice.
- Create the following structure with PowerShell:
project/
├── notes/
├── archives/
└── temp/
- In the
notesfolder, create 3 text files namedcourse1.txt,course2.txt,course3.txt. Each of these files must contain a different sentence, including the word important in one of them. Insert the content directly into the files with PowerShell. - In the
tempfolder, create a text file namedtemp.txtwith the following content:This file is temporary.
Useful commands:
New-Itemto create files and foldersSet-Contentto write content into filesGet-ChildItemto list files and folders
📂 Step 2 – Searches and paths
- Search for all
.txtfiles in theprojectfolder, including subfolders. - Search for the word
importantin all text files. - Display the absolute path of each
.txtfile.
Useful commands:
Get-ChildItem -Recurseto list files recursivelySelect-Stringto search for text in filesResolve-Pathto get the absolute path of files
🔄 Step 3 – Automation and simple wrapping
-
Write a PowerShell script named
manage.ps1that performs the following operations:-
Copies all files from
notestoarchives -
Deletes the content of the
tempfolder if it exists (without deletingtempitself) -
Renames the copied files in
archivesby adding_backupbefore.txt- Example:
course1.txt→course1_backup.txt
- Example:
-
Useful commands:
Test-Pathto check the existence of a folder or fileCopy-Itemto copy filesRemove-Itemto delete files or foldersRename-Itemto rename files
Run your script multiple times to ensure it is idempotent (doesn't break if rerun multiple times).
🧪 Step 4 – Automatic verification
Add to your script a command that:
- Counts and displays the number of files in
archives - Displays a message "Success: all files have been backed up." if this number is 3
🔐 Step 5 – NTFS Permissions (access rights)
-
In the
notes/folder, remove the current user's read permission on one of the files. This must be done using PowerShell. -
Try to read this file with
Get-Content. What happens? -
Then restore the permission with PowerShell.
-
Temporarily give the entire
archives/folder read-write permission only (no deletion). -
Then try to delete a file from
archives/withRemove-Item. What do you observe?