Within the SCOM console there is the option to Uninstall, Repair and Delete an agent from the Agent Managed view. However, when using the Operations Manager cmdlets in PowerShell, it is only possible to Uninstall or Repair. In most cases these options are fine, but there are times when servers go offline unexpectantly, or as part of certain processes, where an agent needs to be Deleted from the SCOM management group.
As there is no cmdlet to delete an agent, the SDK will need to be used in order to achieve this. This script below will delete any single agent specified.
$MGConnSetting = New-Object Microsoft.EnterpriseManagement.ManagementGroupConnectionSettings("<ManagementServerFQDN>")
$MG = New-Object Microsoft.EnterpriseManagement.ManagementGroup($MGConnSetting)
$Admin = $MG.Administration
$agentManagedComputerType = [Microsoft.EnterpriseManagement.Administration.AgentManagedComputer];
$genericListType = [System.Collections.Generic.List``1]
$genericList = $genericListType.MakeGenericType($agentManagedComputerType)
$agentList = new-object $genericList.FullName
#Replace DNSHostName with FQDN of agent to be deleted.
#ComputerName is a SCOM management server to query
$agent = Get-SCOMAgent -DNSHostName "<AgentFQDN>" -ComputerName <ManagementServerFQDN>
$genericReadOnlyCollectionType = [System.Collections.ObjectModel.ReadOnlyCollection``1]
$genericReadOnlyCollection = $genericReadOnlyCollectionType.MakeGenericType($agentManagedComputerType)
$agentReadOnlyCollection = new-object $genericReadOnlyCollection.FullName @(,$agentList);
The script as shown above performs what I need it to as part of an Orchestrator runbook, however it could easily be turned into a function and extended to deal with multiple agent deletions at the same time.
You can also download a copy of the script here.