Script to get the list of VM and there configuration which are hosted in Hyper -V host.
Please find the script below.
# Ensure the Hyper-V module is loaded
Import-Module Hyper-V
# Create the export directory if it doesn't exist
$ExportPath = "C:\Temp\HyperV_VM_List.csv"
if (!(Test-Path "C:\Temp")) {
New-Item -Path "C:\Temp" -ItemType Directory -Force
}
# Get the Hyper-V Host Details
$HostName = $env:COMPUTERNAME
$HostIPConfig = Get-NetIPConfiguration | Where-Object { $_.IPv4Address -ne $null } | Select-Object -First 1
$HostIP = $HostIPConfig.IPv4Address.IPAddress
$Subnet = $HostIPConfig.IPv4Address.PrefixLength
$Gateway = if ($HostIPConfig.IPv4DefaultGateway) { $HostIPConfig.IPv4DefaultGateway.NextHop } else { "N/A" }
$DNS = if ($HostIPConfig.DNSServer) { ($HostIPConfig.DNSServer.ServerAddresses -join ", ") } else { "N/A" }
# Get the list of all VMs on the local Hyper-V host
$VMs = Get-VM
# Initialize an array to store VM details
$VMList = @()
# Loop through each VM and gather details
foreach ($VM in $VMs) {
# Get network adapter details
$VMNetworkAdapters = $VM.NetworkAdapters
$SwitchNames = if ($VMNetworkAdapters) { ($VMNetworkAdapters | ForEach-Object { $_.SwitchName }) -join ", " } else { "N/A" }
$IPAddresses = if ($VMNetworkAdapters) { ($VMNetworkAdapters | ForEach-Object { $_.IPAddresses }) -join ", " } else { "No IP Assigned" }
# Add VM details to the list
$VMList += [PSCustomObject]@{
"Hyper-V Host" = $HostName
"Host IP" = $HostIP
"Subnet" = $Subnet
"Gateway" = $Gateway
"DNS Servers" = $DNS
"VM Name" = $VM.Name
"State" = $VM.State
"CPU Count" = $VM.ProcessorCount
"Memory (GB)" = $VM.MemoryStartup / 1GB
"Generation" = $VM.Generation
"OS" = $VM.GuestOperatingSystem
"Uptime" = $VM.Uptime
"VM ID" = $VM.Id
"Network Adapter" = $SwitchNames
"IP Address" = $IPAddresses
}
}
# Display results in table format
$VMList | Format-Table -AutoSize
# Export results to a CSV file in C:\Temp
$VMList | Export-Csv -Path $ExportPath -NoTypeInformation
Write-Host "VM details exported successfully to $ExportPath"
Please copy the script in Notepad and save as HyperVList.ps1 and then run in any Hyper - V server to get the list of all the vm's and there configuration.
Comments