Introduction
Step 1: Creating a Folder Backup
$sourceFolder = "C:\example\source"
$backupFolder = "C:\example\backup"
Copy-Item -Path $sourceFolder -Destination $backupFolder -Recurse -Force
Step 2: Bulk Renaming Files
$folderPath = "C:\example\files"
$prefix = "new_"
Get-ChildItem -Path $folderPath -Filter *.txt | ForEach-Object {
Rename-Item $_.FullName -NewName ($prefix + $_.Name)
}
Step 3: Monitoring a Folder for Changes
$folder = "C:\example\watched"
$filter = '*.*'
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $folder
$watcher.Filter = $filter
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
Write-Host "File '$path' was $changeType"
}
Register-ObjectEvent -InputObject $watcher -EventName "Created" -Action $action
Register-ObjectEvent -InputObject $watcher -EventName "Changed" -Action $action
while ($true) {
Start-Sleep -Seconds 10
}
Conclusion
You’ve learned how to create PowerShell scripts for everyday tasks, like backing up folders, renaming files in bulk, and monitoring folder changes. Keep exploring and customizing these scripts to fit your needs. Happy scripting! 🚀