Learning Objectives
Below is a PowerShell script that wraps key actions in error handling and logs both success and failure.
- Implement error handling in both PowerCLI and Python scripts.
- Add log file creation for task auditing and troubleshooting.
- Integrate VMware automation scripts with Aria for Logs.
- Visualize end-to-end logging with an diagram.
My Personal Repository on GitHub
try:
completed_process = subprocess.run([
“powershell.exe”,
“-ExecutionPolicy”, “Bypass”,
“-File”, ps_script
], capture_output=True, text=True, timeout=120)
Prerequisites
- Completed Articles 1–5.
- Admin access to your vSphere environment and Aria for Logs (if using log integration).
- PowerCLI, Python, and permissions to write log files.
1. Why Error Handling and Logging Matter
VMware Repository on GitHub
2. PowerCLI Error Handling and Logging
Try/Catch and Log to File
Save as vm_error_handling.ps1
:
if completed_process.returncode == 0:
log_message(“PowerShell script ran successfully.”)
if completed_process.stdout:
log_message(f”Output: {completed_process.stdout}”)
else:
log_message(f”ERROR: {completed_process.stderr}”)
except Exception as e:
log_message(f”Python Exception: {str(e)}”)
def log_message(msg): ps_script = r"C:Tempvm_error_handling.ps1"# Function to log messagesimport subprocess
import datetime# Import PowerCLI
Import-Module VMware.PowerCLI# Try to get VM info
$vms = Get-VM
Log-Message "Successfully retrieved VM inventory. Total: $($vms.Count)"
}
catch {
Log-Message "ERROR: $($_.Exception.Message)"
}
finally {
Disconnect-VIServer -Server * -Confirm:$false
Log-Message "Disconnected from vCenter."
}
# Main workflow
try {
Connect-VIServer -Server <vcenter-address> -User <username> -Password <password> -ErrorAction Stop
Log-Message "Connected to vCenter."
3. Python Error Handling and Logging
with open(logfile, "a") as f:
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"{now} {msg}n")
function Log-Message {
param ([string]$msg)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $logFile -Value "$timestamp $msg"
}You have learned how to add robust error handling and logging to both PowerCLI and Python scripts, and how to centralize logs with Aria for Logs.
This ensures your VMware automation is safer, more auditable, and easier to troubleshoot.By the end of this article, you will:You can configure Windows Event Logs or custom log forwarding.
See VMware docs: Aria for Logs Documentation
4. Integration with Aria for Logs (Optional)
Next up: In Article 7, you will learn about scheduling scripts and automation best practices for production VMware environments.
- Sending logs via syslog from your automation server to Aria for Logs.
- Using a PowerShell or Python module to forward specific events.
For centralized log analysis, send script logs to Aria for Logs.
This is typically accomplished by:
5. Diagram: Logging Workflow

6. Troubleshooting Tips
- Check that your script log file paths exist and are writable.
- For errors not being logged, confirm all actions are inside try/catch blocks.
- To see real-time logs, use
Get-Content -Path C:Tempautomation_log.txt -Wait
in PowerShell.
7. Further Reading
8. Conclusion and Next Steps
Below is a Python wrapper to call the script and log errors or results from the PowerShell execution.
Automation is powerful, but things go wrong: network issues, permissions, resource exhaustion, and more.
Good scripts should log what happened and handle errors gracefully so you know where to look when something fails.