Introduction

Gal Normal

I want to learn how to use PowerShell for everyday tasks. Can you teach me some useful scripts?

Geek Curious

Absolutely! Let's explore some PowerShell scripts that can help you with daily tasks.

Step 1: Creating a Folder Backup

Gal Eager

How about a script to backup a folder?

Geek Ready

Sure thing! Here's a simple script to backup a folder by copying its contents to another folder.

$sourceFolder = "C:\example\source"
$backupFolder = "C:\example\backup"

Copy-Item -Path $sourceFolder -Destination $backupFolder -Recurse -Force
Gal Happy

That's awesome! Now I can backup my files easily! What's next?

Step 2: Bulk Renaming Files

Gal Wondering

Can we do a script to rename multiple files at once?

Geek Nodding

Definitely! Here's a script to rename all .txt files in a folder by adding a prefix.

$folderPath = "C:\example\files"
$prefix = "new_"

Get-ChildItem -Path $folderPath -Filter *.txt | ForEach-Object {
    Rename-Item $_.FullName -NewName ($prefix + $_.Name)
}
Gal Excited

This will save me so much time! Thanks! What else do you have?

Step 3: Monitoring a Folder for Changes

Gal Curious

How about monitoring a folder for changes, like new files or modifications?

Geek Smiling

Great idea! Here's a script that watches a folder and displays a message when a file is created or modified.

$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
}
Gal Amazed

Wow! Now I can keep an eye on my important folders! 🤩

Geek Proud

That's right! PowerShell can make everyday tasks easier and more efficient.

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! 🚀