Dynamic grouping of machines based on "Managed by" Active Directory Attribute
Solution 1:
After some research I found that someone already tackled this problem. Sort of. I modified this script. Got rid of the last couple of lines and added the logic below I needed. It is messy but it works like a charm. All you need to change is the management server and the inclusion regex (we have multiple domains but only want this sort of automation for one).
<Functions from original script go here>
$ManagementServer = "<ManagementServerGoesHere>"
$ManagementGroup = GetSCOMManagementGroup -ms $ManagementServer
$Groups = Get-SCOMGroup -DisplayName "Managed-By *"
$Groups |% {
$Group = $_
$Group.DisplayName -match "Managed-By (\w{3})" | Out-Null
$sAMAccountName = $Matches[1]
$User = Get-ADUser -Filter {sAMAccountName -eq $sAMAccountName}
$UserDN = $User.DistinguishedName
$ADManagedByComputers = Get-ADComputer -Filter {ManagedBy -eq $UserDN}
$SCOMManagedByComputer = Get-SCOMGroup $Group.id | Get-SCOMClassInstance
[string]$InstancesToAdd = ""
[string]$InstancesToRemove = ""
$ADManagedByComputers | % {
if($SCOMManagedByComputer.DisplayName -notcontains $_.DNSHostName) {
$Agent = Get-SCOMAgent -DNSHostName $_.DNSHostName
if($Agent) {
Write-Host ($_.DNSHostName + " not in SCOM Group " + $Group.DisplayName) -ForegroundColor Yellow
$InstancesToAdd = $InstancesToAdd + "," + $Agent.Id
} else {
Write-Host ($_.DNSHostName + " has no Agent installed!") -ForegroundColor Gray
}
} else {
Write-Host ($_.DNSHostname + " already in SCOM Group " + $Group.DisplayName) -ForegroundColor Green
}
}
$SCOMManagedByComputer | % {
if($_.DisplayName -match "<InclusionRegex>") {
if($ADManagedByComputers.DNSHostName -notcontains $_.DisplayName) {
Write-Host ($_.DisplayName + " should not be in SCOM Group " + $Group.DisplayName) -ForegroundColor DarkYellow
$Agent = Get-SCOMAgent -DNSHostName $_.DisplayName
if($Agent) {
$InstancesToRemove = $InstancesToRemove + "," + $Agent.Id
}
}
} else {
Write-Host ($_.DisplayName + " is not in the domain scope. Skipping.") -ForegroundColor Cyan
}
}
$InstancesToAdd = $InstancesToAdd.Trim(",")
$InstancesToRemove = $InstancesToRemove.Trim(",")
$ManagementPackName = ($Group | Get-SCOMClass).ManagementPackName
$ManagementPackID = (Get-SCManagementPack -Name $ManagementPackName)
$MP = ValidateGroup -mg $ManagementGroup -mp $MP -groupID $Group.FullName
If($InstancesToAdd -ne "" -and $InstancesToRemove -ne "") {
$MP = UpdateGroup -mg $ManagementGroup -mp $ManagementPackID -groupID $Group.FullName -instancesToAdd $InstancesToAdd -instancesToRemove $InstancesToRemove
}
if($InstancesToAdd -ne "" -and $InstancesToRemove -eq "") {
$MP = UpdateGroup -mg $ManagementGroup -mp $MP -groupID $Group.FullName -instancesToAdd $InstancesToAdd
}
if($InstancesToAdd -eq "" -and $InstancesToRemove -ne "") {
$MP = UpdateGroup -mg $ManagementGroup -mp $MP -groupID $Group.FullName -instancesToRemove $InstancesToRemove
}
}