Site icon Digital Thought Disruption

PowerCLI and Python Fundamentals for vSphere Automation

Learning Objectives

By the end of this article, you will:


My Personal Repository on GitHub

VMware Repository on GitHub


Prerequisites


1. PowerShell, PowerCLI, and Python — How They Work Together

You can run PowerCLI cmdlets directly in PowerShell, or orchestrate more complex logic by having Python scripts call PowerShell commands.


2. Basic Syntax: PowerShell vs Python

PowerShell Basics

Example:

# List all VMs
Get-VM

# Store VM count in a variable
$vmCount = (Get-VM).Count
Write-Output "There are $vmCount virtual machines."

Python Basics

Example:

# List of VM names
vm_list = ['Web01', 'App01', 'DB01']

# Print how many VMs
print(f"There are {len(vm_list)} virtual machines.")

3. Your First Automated Task: Calling PowerCLI from Python

The simplest way for Python to interact with PowerCLI is by executing PowerShell scripts from within a Python program.

Step 1: Create a PowerShell Script

Let’s start by writing a script that lists all VMs and saves them to a text file.

Save this as list_vms.ps1:

# Import PowerCLI
Import-Module VMware.PowerCLI

# Connect to vCenter (update with your details)
Connect-VIServer -Server <vcenter-address> -User <username> -Password <password>

# List VMs and output to file
Get-VM | Select-Object Name, PowerState | Out-File -FilePath C:\Temp\vm_list.txt

Replace <vcenter-address>, <username>, and <password> with your real values.


Step 2: Execute PowerShell Script from Python

Now, use Python to call that script. Here’s a basic example:

import subprocess

# Define the PowerShell script path
ps_script = r"C:\Temp\list_vms.ps1"

# Run the PowerShell script
completed_process = subprocess.run([
"powershell.exe",
"-ExecutionPolicy", "Bypass",
"-File", ps_script
], capture_output=True, text=True)

# Print the output (if any)
print("Script Output:", completed_process.stdout)
if completed_process.stderr:
print("Errors:", completed_process.stderr)

4. Diagram: Workflow — Python Driving PowerCLI

Legend:


5. Troubleshooting Tips


6. Further Reading


7. Conclusion and Next Steps

You’ve learned the basics of both PowerShell and Python, and you’ve seen how to use Python to execute a PowerCLI script. This opens up a world of automation possibilities, you can now combine VMware commands with Python’s data handling and logic.

In Article 3, you’ll connect to vCenter and retrieve detailed VM info using this combined approach.

Exit mobile version