PowerShell Lesson 6: Scripts and Scheduled Tasks

📎 This article includes 2 downloadable practice files ↓

⏱ 1 min read

📘 PowerShell Beginner Course · Lesson 6 of 6

“`powershell
param([string]$Folder = $env:TEMP, [int]$Days = 30, [switch]$Apply)
$old = Get-ChildItem $Folder -File | Where-Object LastWriteTime -lt (Get-Date).AddDays(-$Days)
“Files older than $Days days in ${Folder}: $(@($old).Count)”
if ($Apply) { $old | Move-Item -Destination (Join-Path $Folder “archive”) }
“`

A param() block makes the script reusable: .\ps-06-scheduled-task.ps1 -Folder C:\Reports -Days 60 -Apply. Without -Apply it only reports (a safe dry run).

Schedule it

“`powershell
$a = New-ScheduledTaskAction -Execute “powershell.exe” -Argument “-File C:\scripts\ps-06-scheduled-task.ps1 -Folder C:\Reports -Apply”
Register-ScheduledTask -TaskName “Archive reports” -Action $a -Trigger (New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 9am)
“`

Or use the Task Scheduler app (Create Basic Task) with the same program and arguments.

💡 Add Start-Transcript -Path C:\scripts\logs\run.log at the top of scheduled scripts so you can see what happened on runs you didn’t watch.

That’s the PowerShell course.

Practice

Run the script in dry-run mode on a folder of your choice.

📎 Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *