PowerShell Schedule Script Automation with Task Scheduler
Every Monday morning at 7 AM, our IT team used to manually run a PowerShell script to generate system health reports for 50+ servers. This meant someone had to be available first thing Monday, remember to run it, wait for completion, then email results.
After implementing scheduled automation with Task Scheduler, this entire workflow now runs automatically:
- Scripts execute at scheduled times (no human required)
- Runs even when no one is logged in
- Emails reports automatically on completion
- Logs successes and failures for auditing
What took 30 minutes of manual work every week now runs itself. This tutorial shows you how to schedule any PowerShell script to run automatically, whether daily, weekly, on specific triggers, or in response to system events.
Why Schedule PowerShell Scripts?
Manual script execution has major drawbacks:
Problems with Manual Execution:
- Requires someone to remember and run scripts
- Can't run overnight or on weekends (unless someone's working)
- Doesn't work during vacations or sick days
- Inconsistent timing (ran at 8 AM today, 10 AM tomorrow)
- No automatic retry if failures occur
Benefits of Scheduled Automation:
- ✅ Scripts run at exact times, every time
- ✅ Execute even when no one is logged in
- ✅ Runs overnight or during off-hours
- ✅ Consistent, reliable execution
- ✅ Built-in logging and error handling
- ✅ Can trigger on events (startup, user login, file changes)
Understanding Windows Task Scheduler
Task Scheduler is Windows' built-in automation framework. It can:
- Run programs/scripts on schedules (daily, weekly, monthly, one-time)
- Trigger based on events (startup, login, system events, file changes)
- Run with elevated privileges (as administrator)
- Execute when no user is logged in
- Retry failed tasks automatically
- Send email notifications (though SMTP setup required)
- Log all executions for audit trails
Task Scheduler Basics:
Trigger: What causes the task to run (time, event, condition) Action: What the task does (run a script, start a program) Conditions: Optional requirements (idle, AC power, network connection) Settings: Behavior rules (retry attempts, execution time limits)
Method 1: Scheduling via Task Scheduler GUI
Let's start with the GUI approach for beginners.
Example: Daily System Health Check
Scenario: Run a system health check every weekday at 8 AM.
Step 1: Create the PowerShell Script
Save this as C:\Scripts\SystemHealthCheck.ps1:
1# SystemHealthCheck.ps12# Daily system health monitoring script34# Set up logging5$LogFile = "C:\Scripts\Logs\HealthCheck_$(Get-Date -Format 'yyyyMMdd').txt"6$ErrorLog = "C:\Scripts\Logs\HealthCheck_Errors_$(Get-Date -Format 'yyyyMMdd').txt"78# Create log directory if it doesn't exist9New-Item -ItemType Directory -Force -Path "C:\Scripts\Logs" | Out-Null1011# Start logging12Start-Transcript -Path $LogFile -Append1314Write-Host "Starting system health check at $(Get-Date)"1516try {17 # Check disk space18 Write-Host "`nChecking disk space..."19 $Disks = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"2021 foreach ($Disk in $Disks) {22 $FreePercent = [math]::Round(($Disk.FreeSpace / $Disk.Size) * 100, 2)2324 if ($FreePercent -lt 10) {25 Write-Warning "Drive $($Disk.DeviceID) is critically low: $FreePercent% free"26 } elseif ($FreePercent -lt 20) {27 Write-Warning "Drive $($Disk.DeviceID) is low on space: $FreePercent% free"28 } else {29 Write-Host "Drive $($Disk.DeviceID): $FreePercent% free - OK"30 }31 }3233 # Check CPU usage34 Write-Host "`nChecking CPU usage..."35 $CPULoad = (Get-CimInstance -ClassName Win32_Processor).LoadPercentage3637 if ($CPULoad -gt 90) {38 Write-Warning "CPU usage is high: $CPULoad%"39 } else {40 Write-Host "CPU usage: $CPULoad% - OK"41 }4243 # Check memory usage44 Write-Host "`nChecking memory usage..."45 $OS = Get-CimInstance -ClassName Win32_OperatingSystem46 $MemoryUsedPercent = [math]::Round((($OS.TotalVisibleMemorySize - $OS.FreePhysicalMemory) / $OS.TotalVisibleMemorySize) * 100, 2)4748 if ($MemoryUsedPercent -gt 90) {49 Write-Warning "Memory usage is high: $MemoryUsedPercent%"50 } else {51 Write-Host "Memory usage: $MemoryUsedPercent% - OK"52 }5354 # Check Windows services (critical services only)55 Write-Host "`nChecking critical services..."56 $CriticalServices = @('wuauserv', 'BITS', 'EventLog', 'Winmgmt')5758 foreach ($ServiceName in $CriticalServices) {59 $Service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue6061 if ($Service.Status -ne 'Running') {62 Write-Warning "Service $ServiceName is not running: $($Service.Status)"63 } else {64 Write-Host "Service $ServiceName: Running - OK"65 }66 }6768 # Check Windows Update status69 Write-Host "`nChecking for pending Windows Updates..."70 $UpdateSession = New-Object -ComObject Microsoft.Update.Session71 $UpdateSearcher = $UpdateSession.CreateUpdateSearcher()72 $SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software'")7374 if ($SearchResult.Updates.Count -gt 0) {75 Write-Warning "$($SearchResult.Updates.Count) Windows Updates pending installation"76 } else {77 Write-Host "Windows Updates: Up to date - OK"78 }7980 Write-Host "`nSystem health check completed successfully at $(Get-Date)"8182} catch {83 Write-Error "Health check failed: $_"84 $_ | Out-File -FilePath $ErrorLog -Append85 throw86}8788Stop-Transcript8990# Optional: Send email report91# Configure SMTP settings first92<#93$EmailParams = @{94 To = 'admin@company.com'95 From = 'healthcheck@company.com'96 Subject = "System Health Check - $(Get-Date -Format 'yyyy-MM-dd')"97 Body = Get-Content $LogFile -Raw98 SmtpServer = 'smtp.company.com'99}100Send-MailMessage @EmailParams101#>
Step 2: Create the Scheduled Task
-
Press Win + R, type
taskschd.msc, press Enter (opens Task Scheduler) -
In the right panel, click Create Task (not "Create Basic Task")
-
General Tab:
- Name:
Daily System Health Check - Description:
Runs PowerShell health check script weekdays at 8 AM - Security options:
- Select "Run whether user is logged on or not"
- Check "Run with highest privileges" (if script needs admin rights)
- Configure for: Windows 10 / Windows Server 2016 (or your OS)
- Name:
-
Triggers Tab:
- Click New
- Begin the task: On a schedule
- Settings: Daily
- Start: 8:00:00 AM
- Recur every: 1 days
- Advanced settings:
- Check "Stop task if it runs longer than: 1 hour" (adjust based on script)
- Click OK
-
Actions Tab:
- Click New
- Action: Start a program
- Program/script:
powershell.exe - Add arguments:
-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\SystemHealthCheck.ps1" - Click OK
-
Conditions Tab (optional but recommended):
- Power: Uncheck "Start the task only if the computer is on AC power" (for laptops)
- Network: Check "Start only if the following network connection is available" > Select appropriate network type if script needs network
-
Settings Tab:
- Check "Allow task to be run on demand" (lets you test manually)
- Check "Run task as soon as possible after a scheduled start is missed" (catches up if computer was off)
- Check "If the task fails, restart every: 1 minute, Attempt to restart up to: 3 times"
- Stop the task if it runs longer than: 1 hour (adjust based on your script)
-
Click OK
-
You'll be prompted to enter the password for the account that will run the task
Step 3: Test the Task
- Right-click your new task in Task Scheduler
- Select Run
- Check
C:\Scripts\Logs\for output
Understanding the PowerShell Arguments
-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\SystemHealthCheck.ps1"
-NoProfile: Don't load user PowerShell profile (faster startup, fewer dependencies)
-ExecutionPolicy Bypass: Ignore execution policy for this run (prevents "script not digitally signed" errors)
-File: Specifies the script to run
Alternative if you need output visible:
-NoProfile -ExecutionPolicy Bypass -WindowStyle Normal -File "C:\Path\To\Script.ps1"
Method 2: Scheduling via PowerShell
For repeatable deployments or multiple machines, create tasks using PowerShell cmdlets.
Creating Scheduled Tasks with PowerShell
Example: Schedule Weekly Backup Script
1# Define the scheduled task parameters2$TaskName = "Weekly Database Backup"3$Description = "Backs up databases every Sunday at 2 AM"4$ScriptPath = "C:\Scripts\DatabaseBackup.ps1"5$LogPath = "C:\Scripts\Logs"67# Ensure log directory exists8New-Item -ItemType Directory -Force -Path $LogPath | Out-Null910# Define the action (what to run)11$Action = New-ScheduledTaskAction `12 -Execute 'powershell.exe' `13 -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$ScriptPath`""1415# Define the trigger (when to run)16# Weekly on Sunday at 2:00 AM17$Trigger = New-ScheduledTaskTrigger `18 -Weekly `19 -DaysOfWeek Sunday `20 -At 2:00AM2122# Define settings (how it behaves)23$Settings = New-ScheduledTaskSettingsSet `24 -AllowStartIfOnBatteries `25 -DontStopIfGoingOnBatteries `26 -StartWhenAvailable `27 -RunOnlyIfNetworkAvailable `28 -ExecutionTimeLimit (New-TimeSpan -Hours 2)2930# Define principal (who runs it)31$Principal = New-ScheduledTaskPrincipal `32 -UserId "SYSTEM" `33 -LogonType ServiceAccount `34 -RunLevel Highest3536# Register the task37Register-ScheduledTask `38 -TaskName $TaskName `39 -Description $Description `40 -Action $Action `41 -Trigger $Trigger `42 -Settings $Settings `43 -Principal $Principal `44 -Force4546Write-Host "Scheduled task '$TaskName' created successfully"4748# Verify the task exists49Get-ScheduledTask -TaskName $TaskName | Format-List *
Common Trigger Types
Daily at specific time:
1$Trigger = New-ScheduledTaskTrigger -Daily -At 3:00AM
Weekly on multiple days:
1$Trigger = New-ScheduledTaskTrigger `2 -Weekly `3 -DaysOfWeek Monday, Wednesday, Friday `4 -At 9:00AM
Monthly on specific day:
1$Trigger = New-ScheduledTaskTrigger `2 -Monthly `3 -DaysOfMonth 1 `4 -At 12:00AM
At system startup:
1$Trigger = New-ScheduledTaskTrigger -AtStartup
At user logon:
1$Trigger = New-ScheduledTaskTrigger -AtLogon
On idle (computer has been inactive):
1$Trigger = New-ScheduledTaskTrigger -OnIdle
Multiple triggers (run on schedule OR at startup):
1$Trigger1 = New-ScheduledTaskTrigger -Daily -At 3:00AM2$Trigger2 = New-ScheduledTaskTrigger -AtStartup34Register-ScheduledTask `5 -TaskName "Multi-Trigger Task" `6 -Action $Action `7 -Trigger @($Trigger1, $Trigger2) `8 -Settings $Settings
Real-World Automation Examples
Example 1: Automated Daily Report Generation
Scenario: Generate and email a sales report every weekday at 7 AM.
Script: C:\Scripts\DailySalesReport.ps1
1# DailySalesReport.ps12# Generates daily sales report and emails to management34$LogFile = "C:\Scripts\Logs\SalesReport_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"5Start-Transcript -Path $LogFile67try {8 Write-Host "Generating sales report for $(Get-Date -Format 'yyyy-MM-dd')"910 # Connect to database (example with SQL Server)11 $ConnectionString = "Server=SQLSERVER01;Database=SalesDB;Integrated Security=True;"12 $Connection = New-Object System.Data.SqlClient.SqlConnection($ConnectionString)13 $Connection.Open()1415 # Query sales data16 $Query = @"17 SELECT18 ProductName,19 SUM(Quantity) AS UnitsSold,20 SUM(TotalAmount) AS Revenue21 FROM Sales22 WHERE SaleDate = CAST(GETDATE() AS DATE)23 GROUP BY ProductName24 ORDER BY Revenue DESC25"@2627 $Command = New-Object System.Data.SqlClient.SqlCommand($Query, $Connection)28 $Adapter = New-Object System.Data.SqlClient.SqlDataAdapter($Command)29 $DataTable = New-Object System.Data.DataTable30 $Adapter.Fill($DataTable) | Out-Null31 $Connection.Close()3233 # Generate HTML report34 $HTMLReport = $DataTable | ConvertTo-Html -Title "Daily Sales Report" -PreContent "<h1>Daily Sales Report - $(Get-Date -Format 'yyyy-MM-dd')</h1>" | Out-String3536 # Calculate summary stats37 $TotalRevenue = ($DataTable | Measure-Object -Property Revenue -Sum).Sum38 $TotalUnits = ($DataTable | Measure-Object -Property UnitsSold -Sum).Sum3940 $HTMLReport += "<h2>Summary</h2><p>Total Revenue: `$$($TotalRevenue.ToString('N2'))<br>Total Units Sold: $TotalUnits</p>"4142 # Send email43 $EmailParams = @{44 To = @('sales@company.com', 'management@company.com')45 From = 'reports@company.com'46 Subject = "Daily Sales Report - $(Get-Date -Format 'yyyy-MM-dd')"47 Body = $HTMLReport48 BodyAsHtml = $true49 SmtpServer = 'smtp.company.com'50 Port = 58751 UseSsl = $true52 Credential = New-Object System.Management.Automation.PSCredential(53 'reports@company.com',54 (ConvertTo-SecureString 'YourPassword' -AsPlainText -Force)55 )56 }5758 Send-MailMessage @EmailParams5960 Write-Host "Report generated and emailed successfully"6162} catch {63 Write-Error "Report generation failed: $_"6465 # Send failure notification66 Send-MailMessage `67 -To 'admin@company.com' `68 -From 'reports@company.com' `69 -Subject 'FAILED: Daily Sales Report' `70 -Body "Report generation failed. Error: $_" `71 -SmtpServer 'smtp.company.com'7273 throw74} finally {75 Stop-Transcript76}
Create scheduled task:
1$Action = New-ScheduledTaskAction `2 -Execute 'powershell.exe' `3 -Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\DailySalesReport.ps1"'45$Trigger = New-ScheduledTaskTrigger `6 -Weekly `7 -DaysOfWeek Monday, Tuesday, Wednesday, Thursday, Friday `8 -At 7:00AM910$Settings = New-ScheduledTaskSettingsSet `11 -StartWhenAvailable `12 -RunOnlyIfNetworkAvailable `13 -ExecutionTimeLimit (New-TimeSpan -Hours 1)1415$Principal = New-ScheduledTaskPrincipal `16 -UserId "DOMAIN\ServiceAccount" `17 -LogonType Password `18 -RunLevel Highest1920Register-ScheduledTask `21 -TaskName "Daily Sales Report" `22 -Action $Action `23 -Trigger $Trigger `24 -Settings $Settings `25 -Principal $Principal
Example 2: Cleanup Old Files Monthly
Scenario: Delete log files older than 90 days, first day of each month.
Script: C:\Scripts\CleanupOldLogs.ps1
1# CleanupOldLogs.ps12# Deletes log files older than 90 days34$LogPath = "C:\Logs"5$RetentionDays = 906$CurrentDate = Get-Date7$DeleteBefore = $CurrentDate.AddDays(-$RetentionDays)89Write-Host "Starting log cleanup for files older than $RetentionDays days"10Write-Host "Delete cutoff date: $DeleteBefore"1112# Get old log files13$OldFiles = Get-ChildItem -Path $LogPath -Recurse -File |14 Where-Object { $_.LastWriteTime -lt $DeleteBefore }1516$TotalSize = ($OldFiles | Measure-Object -Property Length -Sum).Sum17$TotalSizeGB = [math]::Round($TotalSize / 1GB, 2)1819Write-Host "Found $($OldFiles.Count) files to delete (Total: $TotalSizeGB GB)"2021if ($OldFiles.Count -gt 0) {22 $OldFiles | Remove-Item -Force -ErrorAction SilentlyContinue23 Write-Host "Cleanup complete. Freed up $TotalSizeGB GB of space"24} else {25 Write-Host "No files to delete"26}
Schedule to run monthly:
1$Trigger = New-ScheduledTaskTrigger -Monthly -DaysOfMonth 1 -At 1:00AM23Register-ScheduledTask `4 -TaskName "Monthly Log Cleanup" `5 -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\CleanupOldLogs.ps1"') `6 -Trigger $Trigger `7 -Settings (New-ScheduledTaskSettingsSet) `8 -User "SYSTEM"
Example 3: Startup Script - Start Services
Scenario: Ensure critical application services start on system boot.
Script: C:\Scripts\StartupServices.ps1
1# StartupServices.ps12# Ensures critical services are running at startup34$LogFile = "C:\Scripts\Logs\StartupServices_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"5Start-Transcript -Path $LogFile67$CriticalServices = @(8 'MyAppService',9 'MyDatabaseService',10 'MyWebService'11)1213Write-Host "Checking critical services at $(Get-Date)"1415foreach ($ServiceName in $CriticalServices) {16 try {17 $Service = Get-Service -Name $ServiceName -ErrorAction Stop1819 if ($Service.Status -ne 'Running') {20 Write-Host "Starting service: $ServiceName"21 Start-Service -Name $ServiceName -ErrorAction Stop2223 # Wait for service to start24 $Service.WaitForStatus('Running', (New-TimeSpan -Seconds 30))25 Write-Host "Service $ServiceName started successfully"26 } else {27 Write-Host "Service $ServiceName is already running"28 }29 } catch {30 Write-Error "Failed to start service $ServiceName : $_"31 }32}3334Stop-Transcript
Schedule at startup:
1$Trigger = New-ScheduledTaskTrigger -AtStartup23# Add delay to let system stabilize4$Settings = New-ScheduledTaskSettingsSet -Delay (New-TimeSpan -Minutes 2)56Register-ScheduledTask `7 -TaskName "Startup Services Check" `8 -Action (New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\StartupServices.ps1"') `9 -Trigger $Trigger `10 -Settings $Settings `11 -User "SYSTEM" `12 -RunLevel Highest
Advanced Scheduling Techniques
Event-Triggered Tasks
Run scripts in response to Windows Event Log entries:
1# Create task that runs when Event ID 1074 (system restart) is logged23# Create CIM trigger for event4$Class = Get-CimClass -ClassName MSFT_TaskEventTrigger -Namespace Root/Microsoft/Windows/TaskScheduler5$Trigger = New-CimInstance -CimClass $Class -ClientOnly67$Trigger.Enabled = $true8$Trigger.Subscription = @"9<QueryList>10 <Query Id="0" Path="System">11 <Select Path="System">*[System[Provider[@Name='User32'] and EventID=1074]]</Select>12 </Query>13</QueryList>14"@1516$Action = New-ScheduledTaskAction `17 -Execute 'powershell.exe' `18 -Argument '-NoProfile -File "C:\Scripts\OnRebootNotify.ps1"'1920Register-ScheduledTask `21 -TaskName "Notify on System Reboot" `22 -Action $Action `23 -Trigger $Trigger
Running Multiple Scripts in Sequence
Create a wrapper script to orchestrate multiple scripts:
1# MasterSchedule.ps12# Runs multiple scripts in sequence with error handling34$Scripts = @(5 'C:\Scripts\Step1_Backup.ps1',6 'C:\Scripts\Step2_Process.ps1',7 'C:\Scripts\Step3_Report.ps1'8)910foreach ($Script in $Scripts) {11 Write-Host "`nRunning: $Script"1213 try {14 & $Script1516 if ($LASTEXITCODE -ne 0) {17 throw "Script exited with code $LASTEXITCODE"18 }1920 Write-Host "Completed successfully: $Script"2122 } catch {23 Write-Error "Script failed: $Script - $_"2425 # Stop execution on first failure26 throw "Master schedule aborted due to failure in $Script"27 }28}2930Write-Host "`nAll scripts completed successfully"
Troubleshooting Scheduled Tasks
Common Issues and Solutions
Issue: Task shows "Last Run Result: 0x1" (error)
Solutions:
- Check execution policy:
Get-ExecutionPolicy - Verify script path is absolute, not relative
- Ensure account has permissions to run script and access resources
- Check logs in
C:\Windows\System32\winevt\Logs\Microsoft-Windows-TaskScheduler%4Operational.evtx
Issue: Task doesn't run when user is not logged in
Solutions:
- Ensure "Run whether user is logged on or not" is selected
- Use a service account with "Log on as a batch job" rights
- Check "Run with highest privileges" if admin rights needed
Issue: Script runs manually but not via Task Scheduler
Solutions:
- Task Scheduler uses different environment variables
- Use absolute paths for all files (no relative paths)
- Set "Start in" directory in Action settings
- Add error handling and logging to script
Issue: Task runs but produces no output/logs
Solutions:
- Verify log directory exists and account has write permissions
- Use
Start-Transcriptto capture all output - Redirect errors:
2>&1 | Out-File "C:\Logs\output.txt"
Debugging Scheduled Tasks
Add detailed logging to your scripts:
1# Enhanced logging template2$ScriptName = "MyScript"3$LogDir = "C:\Scripts\Logs"4$LogFile = Join-Path $LogDir "$ScriptName_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"56# Ensure log directory exists7New-Item -ItemType Directory -Force -Path $LogDir | Out-Null89Start-Transcript -Path $LogFile -Append1011Write-Host "========================================"12Write-Host "Script: $ScriptName"13Write-Host "Start Time: $(Get-Date)"14Write-Host "User: $env:USERNAME"15Write-Host "Computer: $env:COMPUTERNAME"16Write-Host "========================================"1718try {19 # Your script logic here20 Write-Host "Script execution successful"2122} catch {23 Write-Error "Script failed: $_"24 Write-Error $_.Exception.StackTrace25 throw2627} finally {28 Write-Host "End Time: $(Get-Date)"29 Stop-Transcript30}
Monitoring Task Execution
Query scheduled task history:
1# Get last run status of all tasks2Get-ScheduledTask | Where-Object {$_.State -ne 'Disabled'} | Get-ScheduledTaskInfo |3 Select-Object TaskName, LastRunTime, LastTaskResult |4 Format-Table -AutoSize56# Get failed tasks7Get-ScheduledTask | Where-Object {$_.State -ne 'Disabled'} | Get-ScheduledTaskInfo |8 Where-Object {$_.LastTaskResult -ne 0} |9 Select-Object TaskName, LastRunTime, LastTaskResult
Security Best Practices
1. Use Service Accounts
Don't run scheduled tasks under personal user accounts:
1# Create a dedicated service account (run in elevated prompt)2New-LocalUser -Name "TaskSchedulerService" -Description "Service account for scheduled tasks" -NoPassword3Add-LocalGroupMember -Group "Users" -Member "TaskSchedulerService"45# Grant "Log on as a batch job" right via Local Security Policy
2. Secure Credentials
Never hardcode passwords in scripts:
Bad:
1$Password = "MyPassword123"
Good (use Windows Credential Manager):
1# Store credential once2$Credential = Get-Credential3$Credential.Password | ConvertFrom-SecureString | Out-File "C:\Scripts\Secure\cred.txt"45# Use in scripts6$SecurePassword = Get-Content "C:\Scripts\Secure\cred.txt" | ConvertTo-SecureString7$Credential = New-Object System.Management.Automation.PSCredential("username", $SecurePassword)
3. Limit Script Permissions
Use principle of least privilege:
- Only grant necessary permissions
- Run with standard user account when possible
- Use "Run with highest privileges" only when required
##Frequently Asked Questions
Can I schedule scripts on remote computers?
Yes, use Register-ScheduledTask with -CimSession:
1$Session = New-CimSession -ComputerName "RemotePC01"23Register-ScheduledTask `4 -TaskName "Remote Task" `5 -Action $Action `6 -Trigger $Trigger `7 -CimSession $Session
How do I export/import scheduled tasks?
Export:
1Export-ScheduledTask -TaskName "MyTask" | Out-File "C:\Backup\MyTask.xml"
Import:
1Register-ScheduledTask -Xml (Get-Content "C:\Backup\MyTask.xml" | Out-String) -TaskName "MyTask"
Can tasks wake the computer from sleep?
Yes, in Conditions tab, check "Wake the computer to run this task". Note: Works with sleep, not hibernate/shutdown.
How do I see task history?
In Task Scheduler GUI: Select task > History tab. Or via PowerShell:
1Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational |2 Where-Object {$_.TaskName -eq '\MyTask'} |3 Select-Object TimeCreated, Message
Related articles: PowerShell File Organization Script, Automate Windows Cleanup with PowerShell
Sponsored Content
Interested in advertising? Reach automation professionals through our platform.