Site icon Digital Thought Disruption

Connecting to vCenter/ESXi and Retrieving VM Information with PowerCLI and Python

Learning Objectives

By the end of this article, you will:


My Personal Repository on GitHub

VMware Repository on GitHub


Prerequisites


1. The PowerCLI Connection Workflow

To automate VMware, you first need to connect to the environment.
PowerCLI uses the Connect-VIServer cmdlet to establish a secure session with vCenter or ESXi.


2. Example: PowerShell Script to Connect and Retrieve VM Information

Let’s create a script that:

Save this as get_vm_info.ps1:

# Import PowerCLI
Import-Module VMware.PowerCLI

# Disable certificate warnings for test labs (not recommended in production)
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$false

# Connect to vCenter or ESXi (update credentials)
Connect-VIServer -Server <vcenter-address> -User <username> -Password <password>

# Get VM info: Name, PowerState, Guest OS, IP Address
Get-VM | Select-Object Name, PowerState, @{N="GuestOS";E={$_.Guest.OSFullName}}, @{N="IPAddress";E={$_.Guest.IPAddress -join ', '}} |
Export-Csv -Path C:\Temp\vm_inventory.csv -NoTypeInformation

# Disconnect when done
Disconnect-VIServer -Server * -Confirm:$false

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


3. Calling the PowerShell Script from Python

Use Python to automate running the PowerShell script:

import subprocess

ps_script = r"C:\Temp\get_vm_info.ps1"

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

print("Script Output:", completed_process.stdout)
if completed_process.stderr:
print("Errors:", completed_process.stderr)

This will generate C:\Temp\vm_inventory.csv containing your VM details.


4. Diagram: End-to-End VM Inventory Automation

Legend:


5. Viewing and Using the VM Inventory Output

Once the script completes, open C:\Temp\vm_inventory.csv with Excel or any CSV viewer.
Each row represents a VM, with columns for Name, PowerState, Guest OS, and IP Address.


6. Troubleshooting and Best Practices


7. Further Reading

VMware PowerCLI Documentation:

Python subprocess docs:

PowerShell Official Docs:

Credential Manager Module:


8. Conclusion and Next Steps

You have learned how to connect to vCenter or ESXi using PowerCLI, retrieve VM inventory, and automate everything with Python.
This workflow forms the foundation for reporting, auditing, and further automation across your VMware estate.

Next up: In Article 4, you will learn how to automate VM lifecycle actions and snapshots, taking your scripting skills to the next level.

Exit mobile version