Powershell script to get Hyper-V VM inventory
Hi
If you have a Hyper-V hypervisor, and you want to have an idea of the configurations of each VM and then you want to make modifications in Excel on all this information, I share with you a script that allows you to collect quite a lot of information and make calculations on all the VMs of your hypervisor (machine name, state, Operating System, OS Build Number, processor, RAM, Total Disk Size, Total Free Space...etc).
I wrote this script and tested it a long time ago, but unfortunately I can't test it anymore because I don't have a Hyperv server to do so.
The resulting CSV file will be saved in the C:\Report folder.
Test it and tell me what you think in the comments.
The script must be executed directly on hypervisor and you need to change the hypervisor name (HyperV-ServerName) before executing the script.
领英推荐
Here's the script :
$ErrorActionPreference = "Stop"
if((Test-Path "C:\Repoprt\") -eq $false)
{
New-Item -Path "C:\Repoprt\" -ItemType directory
}
# Folder to save CSV file
$outputFile = "C:\Repoprt\VM-Inventory.csv"
# Hyper-v server name
$Hyperv_Server = "HyperV-ServerName"
# Get list of hyperv VMs
$VMs = Get-VM -ComputerName $Hyperv_Server
$Operating_System = ''
$Build_Number = 0
foreach ($VM in $VMs)
{
if($VM.State -eq "Running")
{
$cpmputer = $VM.VMName
try
{
if(Test-WSMan -ComputerName $cpmputer)
{
$OS = Get-CimInstance -ComputerName $VM.VMName -class Win32_OperatingSystem | Select-Object Caption , BuildNumber
$Operating_System = $OS.caption
$Build_Number = $OS.BuildNumber
}
}
catch
{
$Operating_System = 'Linux / Autre OS'
$Build_Number = 0
}
}
else
{
$Operating_System = 'Machine OFF'
}
# Put results in to array
[array] $Result2 = Get-VM -ComputerName $Hyperv_Server | Where-Object Name -eq $cpmputer | Select-Object -Property VMId |
Get-VHD | Select-Object @{label='Disk Size (GB)';expression={$_.Size/1gb –as [int]}}, `
@{label='Used (GB)';expression={$_.FileSize/1gb –as [int]}}, @{label='Remaining Space (GB)';expression={($_.Size/1gb - $_.FileSize/1gb) –as [int]}}
#Write-Host "Count = $($Result2.Count)"
#$Result2.Count
[int]$TotalDiskSize = 0
[int]$FreeDiskSpace = 0
if($Result2.Count -gt 0)
{
foreach ($hdd in $Result2)
{
$TotalDiskSize = $TotalDiskSize + $hdd.'Disk Size (GB)'
$FreeDiskSpace = $FreeDiskSpace + $hdd.'Remaining Space (GB)'
}
}
# Export Result to csv file
$VM | Select-Object Name , state, ProcessorCount, @{label = 'RAM' ; expression = {$_.MemoryStartup / 1GB -as [int]}} , @{label = 'Operating System' ; expression = {$Operating_System}}, @{label = 'OS Build Number' ; expression = { $Build_Number }}, @{label = 'Total Disk Size' ; expression = {$TotalDiskSize}} , @{label = 'Total Free Space' ; expression = {$FreeDiskSpace}} |
Export-Csv -Path $outputFile -Delimiter ";" -NoTypeInformation -Append
}
Thanks
Aymen EL JAZIRI