Introduction

crontab -l


Diagram: PowerCLI Scheduling Workflow


Step 4: Use Credential Storage Securely

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

  • Create reusable PowerCLI scripts
  • Use Windows Task Scheduler to run scripts daily or weekly
  • Use cron on Linux/macOS with PowerShell Core
  • Secure credentials and log output
  • Build a scheduling strategy for DR, audits, or cleanup jobs

Step 1: Prepare a PowerCLI Script

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

# C:ScriptsCleanupSnapshots.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

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.


Step 3: Schedule Script Using cron on Linux or macOS

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

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


Use Case: Schedule Weekly Snapshot Cleanup

In this article, you will learn to:

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

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

Validate with:


Step 5: Add Logging to Your Script

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

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

Test manually in PowerShell before scheduling.


Troubleshooting

Problem Fix
Script does not run from Scheduler Use full path to script and include -ExecutionPolicy Bypass
Cron job not executing Use absolute paths and redirect stderr to a log file
Credentials not accepted Use credential store, not plain-text password in the script
Task fails with access denied Check task is set to run with elevated privileges

Similar Posts