Site icon Digital Thought Disruption

How to Schedule a PowerCLI Script with Task Scheduler or cron

Introduction

PowerCLI is powerful when used interactively, but it becomes transformative when scheduled. From snapshot audits to VM reports, regular automation increases consistency and saves time. You can schedule any PowerCLI script using native tools like Windows Task Scheduler or cron in Linux/macOS environments.

In this article, you will learn to:


Step 1: Prepare a PowerCLI Script

Save your automation script with a .ps1 extension. For example:

# C:\Scripts\VM-Report.ps1
Connect-VIServer -Server "vcenter.lab.local"
Get-VM | Select Name, PowerState, VMHost | Export-Csv "C:\Reports\VM_Report.csv" -NoTypeInformation
Disconnect-VIServer * -Confirm:$false

Test manually in PowerShell before scheduling.


Step 2: Schedule Script Using Windows Task Scheduler

A. Open Task Scheduler

B. General Tab

C. Triggers Tab

D. Actions Tab

E. Conditions & Settings

Click OK, enter credentials, and you’re done.


Step 3: Schedule Script Using cron on Linux or macOS

PowerCLI works with PowerShell Core. Use crontab -e to add a job:

0 2 * * * pwsh -File /home/user/scripts/backup-report.ps1 >> /home/user/scripts/cron.log 2>&1

This runs every day at 2:00 AM and logs output to a file.

Validate with:

crontab -l

Diagram: PowerCLI Scheduling Workflow


Step 4: Use Credential Storage Securely

Use Windows Credential Manager with New-VICredentialStoreItem:

New-VICredentialStoreItem -Host "vcenter.lab.local" -User "admin@lab.local" -Password "MySecurePassword"

Then your script can connect silently:

Connect-VIServer -Server "vcenter.lab.local" -User "admin@lab.local"

On Linux/macOS, use Get-Credential with a prompt or environment variable workaround.


Step 5: Add Logging to Your Script

$log = "C:\Logs\VM_Report_$(Get-Date -Format yyyyMMdd_HHmm).log"
"Report started at $(Get-Date)" | Out-File $log
Get-VM | Select Name, PowerState | Export-Csv "C:\Reports\DailyVMs.csv" -NoTypeInformation
"Report complete at $(Get-Date)" | Out-File $log -Append

Use Case: Schedule Weekly Snapshot Cleanup

Create a script:

# C:\Scripts\CleanupSnapshots.ps1
Connect-VIServer -Server "vcenter.lab.local"
Get-VM | Get-Snapshot | Where-Object {$_.Created -lt (Get-Date).AddDays(-14)} | Remove-Snapshot -Confirm:$false
Disconnect-VIServer * -Confirm:$false

Schedule weekly using Windows Task Scheduler (Sunday 3:00 AM).


Troubleshooting

ProblemFix
Script does not run from SchedulerUse full path to script and include -ExecutionPolicy Bypass
Cron job not executingUse absolute paths and redirect stderr to a log file
Credentials not acceptedUse credential store, not plain-text password in the script
Task fails with access deniedCheck task is set to run with elevated privileges
Exit mobile version