The PowerShell function discussed in this article will help you to find out list of Hyper-V servers in Domain.
In today’s post, let us see how to find list of Hyper-V servers in domain. Whenever a Hyper-V server is added to active directory, it creates a Service Connection point (SCP) object in Active Directory under the Hyper-V server computer name with name “Microsoft Hyper-V”. This SCP can be used to discover list of Hyper-V servers in active directory. Both Hyper-V2008 and 2012 exhibit this behavior. Now let us form a script based on this information to get Hyper-V servers in Active Directory.
Code:
function Get-HyperVServersInDomain { [cmdletbinding()] param( ) try { Import-Module ActiveDirectory -ErrorAction Stop } catch { Write-Warning "Failed to import Active Directory module. Exiting" return } try { $Hypervs = Get-ADObject -Filter 'ObjectClass -eq "serviceConnectionPoint" -and Name -eq "Microsoft Hyper-V"' -ErrorAction Stop } catch { Write-Error "Failed to query active directory. More details : $_" } foreach($Hyperv in $Hypervs) { $temp = $Hyperv.DistinguishedName.split(",") $HypervDN = $temp[1..$temp.Count] -join "," $Comp = Get-ADComputer -Id $HypervDN -Prop * $OutputObj = New-Object PSObject -Prop ( @{ HyperVName = $Comp.Name OSVersion = $($comp.operatingSystem) }) $OutputObj } }
In this script I am using a flaky code to get computer DN from SCP DN. I couldn’t find any better way at the moment. Please share if you are aware of any.
Output:
Hope this helps.
Comments on this entry are closed.
This is great and works a treat!
However, I have a need to expand it to query all of the domains in our forest, is there an easy way to do this?
You can query all domains in a forest by using (Get-ADForest).Domains
A small fix to ignore “LostAndFound” directory:
foreach ($Hyperv in $Hypervs) {
$temp = $Hyperv.DistinguishedName.split(“,”)
$HypervDN = $temp[1..$temp.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
}
}
if you want a shorthand variable version it is
$VMHosts = @()
Get-ADObject -Filter ‘ObjectClass -eq “serviceConnectionPoint” -and Name -eq “Microsoft Hyper-V”‘ | %{$VMHosts += ((($_.DistinguishedName.Split(‘,’))[1]) -split ‘CN=’)[1]}
otherwise for just display pursposes remove the $vmhosts variable completely