Forum Discussion
Getting all virtual machines in a Hyper-V cluster using Python and WinRM
Hello,
I am trying to use Python and WinRM to retrieve a list of all virtual machines in a Hyper-V cluster. I have a PowerShell script that works to retrieve the virtual machines owned by the current node, but I am having trouble modifying it to retrieve all virtual machines in the cluster.
Here's the current script that retrieves the virtual machines owned by the current node:
# Create a PowerShell session on the host machine
session = winrm.Session(host, auth=(username, password),transport='ntlm')
# Define the PowerShell command to retrieve the list of virtual machines in the cluster
ps_script = """
$nodes = Get-ClusterNode
Write-Output $nodes
$vm_list = Get-ClusterGroup -Cluster $env:computername | Where-Object {$_.GroupType -eq 'VirtualMachine' -and $_.OwnerNode.Name -in $nodes.Name} | Get-VM
$vm_names = $vm_list.Name
Write-Output $vm_names
"""
# Execute the PowerShell command and retrieve the output
result = session.run_ps(ps_script)
if result.status_code == 0:
# Parse the output to get the list of virtual machines
vm_info = result.std_out.decode('utf-8').strip()
# Print the list of virtual machines
print(vm_info)
else:
# Print the full error message
print("Error message: " + result.std_err.decode('utf-8').strip())
Can anyone help me modify this script to retrieve all virtual machines in the cluster, regardless of which node owns them?
Thank you in advance for your help!
2 Replies
- AndySvintsIron Contributor
Hello amontaser_egid,
Try something like this:
ps_script = """ $vm_list = Get-ClusterGroup -Cluster $env:computername | Where-Object {$_.GroupType -eq 'VirtualMachine'} | Get-VM $vm_names = $vm_list.Name Write-Output $vm_names """
Hope that helps.
- amontaser_egidCopper Contributor
Hello AndySvints, thanks for your help. I try the code but unfortunately, it still retrieves one node VMs, but when I run the script on the hyper-v machine it gets the whole list,