Version 0.03:
https://blog.kimconnect.com/powershell-obtain-list-of-hyper-v-hosts-via-active-directory/
Version 0.02:
PowerShell: Get NIC MTU’s of All Hyper-V Hosts in Domain/Forest
Previous version:
# listHyperVHostsInForests.ps1
# version 0.01
# This function scans the environment of forests and returns a list of Hyper V Hosts within all domains of those forests. Note that the result shall include the Windows OS version as Hyper-V Managers (HM) are OS dependent (e.g. 2012 HM maynot be able to control 2008 hosts).
# Ensure that AD management module is available for PS Session
if (!(get-module -name "ActiveDirectory") ){
Add-WindowsFeature RSAT-AD-PowerShell | out-null;
import-module -name "ActiveDirectory" -DisableNameChecking | out-null;
}
function List-hyperVHosts {
[cmdletbinding()]
param(
[string]$forest
)
try {
Import-Module ActiveDirectory -ErrorAction Stop
} catch {
Write-Warning "Failed to import Active Directory module. Cannot continue. Aborting..."
break;
}
$domains=(Get-ADForest -Identity $forest).Domains
foreach ($domain in $domains){
#"$domain`: `n"
[string]$dc=(get-addomaincontroller -DomainName $domain -Discover -NextClosestSite).HostName
try {
$hyperVs = Get-ADObject -Server $dc -Filter 'ObjectClass -eq "serviceConnectionPoint" -and Name -eq "Microsoft Hyper-V"' -ErrorAction Stop;
} catch {
"Failed to query $dc of $domain";
}
foreach($hyperV in $hyperVs) {
$x = $hyperV.DistinguishedName.split(",")
$HypervDN = $x[1..$x.Count] -join ","
if ( !($HypervDN -match "CN=LostAndFound")) {
$Comp = Get-ADComputer -Id $HypervDN -Prop *
$OutputObj = New-Object PSObject -Prop (
@{
HyperVName = $Comp.Name
OSVersion = $($comp.operatingSystem)
})
$OutputObj
}
}
}
}
function listForests{
$GLOBAL:forests=Get-ADForest | select Name;
if ($forests.length -gt 1){
#for ($i=0;$i -lt $forests.length;$i++){$forests[$i].Name;}
$forests | %{$_.Name;}
}else{
$forests.Name;
}
}
function listHyperVHostsInForests{
listForests|%{List-HyperVHosts $_}
}
listHyperVHostsInForests;
Sample Output:
PS C:\WINDOWS\system32> List-HyperVHosts
KIMCONNECT.COM:
OSVersion HyperVName
--------- ----------
Windows Server 2016 Standard HYPERV01
Windows Server 2008 R2 Enterprise HYPERV02
Hyper-V Server HYPERV03
Hyper-V Server 2012 R2 HYPERV04
Windows Server 2012 R2 Standard HYPERV05
Windows Server 2012 R2 Standard HYPERV06
Categories:
HKLM
Awesome!. You don’t know how long I’ve been looking for this.
HKLS
It is not showing all list, some of the Hyper-v hosts are missing, i have tried with 2k8 & 2k16 server but still result is same. kindly suggest
kimconnect
I’ve made an error on the last function, it’s now corrected as:
function listHyperVHostsInForests{
listForests|%{List-HyperVHosts $_}
}
Please let me know what errors you’re experiencing. Also, one must exec PowerShell as Administrator using credentials of an account with memberships in these groups: Domain Administrators, Enterprise Administrators, and Schema Administrators