Powershell Scritp for Inventory VMS in Hyper-V and VMware
Today I have to create a list of VMS, but with specific information.
Usually you will like some basic info from your virtual machines, including, name, amoutn of CPU, RAM and Disk Usage.
Well... here you will learn how, and using simple lines.
Get a List of VMS from Virtual Machine Manager
If using VMM you can use this method, this will allow a complete list of all hosts and VMS in your environment.
#This get the list of all VMs
$vms = Get-VM -All
#this generate a report including, name, host, status, cpu, ram and disk usage
$Report = $vms | select name, vmhost, status, CPUcount, MemoryAssignedMB, @{Name="DiskAllocated";Expression={[math]::round($_.TotalSize/1024/1024/1024,2)}}
#this export the report as CSV. Now you can take this to Excel.
$Report | Export-CSV -NoTypeInformation -Encoding UTF8 -Path c:\tools\Reporte_VMS.csv
The trick is using a calculated parameter. TotalSize has the Value, I changed the name to "Disk Allocated" and changed the result from bytes to Gigabytes.
Get the List from VMware Powershell CLI
the following will work if you have downloaded and installed the Powershell CLI for vmware.
#First, connecto to your vcenter Server
Connect-VIServer -Server vcenter02.example.com
#Get the list of VMs stored in a variable
$vms2=get-vm
#Get the holy-script to get the used disk of your VM
$Report= $vms2 | select name,Host,PowerState,NumCpu,MemoryGB, @{Name="DiskAllocated";Expression={$_.extensiondata.Storage.PerDatastoreUsage | foreach {$z=$null}{$z+=$_.Committed}{[math]::round($z/1GB,2)}}}
#Esport the results to a CSV file.
$Report | Export-CSV -NoTypeInformation -Encoding UTF8 -Path c:\tools\Reporte_VMS.csv
In this last example, the issue is a little more difficult. As you don't have a value for Total Size, you have to iterate in your VM and get a property called "Committed", but this is stored in your $VM.extensiondata.Storage.PerDatastoreUsage. The issue is when you have multiple disks and this is tored in different datastores. This script sums the values using a variable named "$z"
foreach {$z=$null}{$z+=$_.Committed}{$z}
In order to give this a format, I change to GB and get only 2 decimals:
[math]::round($z/1GB,2)
see you, have a nice scripting.
Comments
Post a Comment