Deleting Agents
A few of you sent mail asking how to delete an agent using the Command Shell. There is a Cmdlet for uninstalling an agent called Uninstall-Agent. However, uninstalling an agent will not work if the computer the agent is hosted by is not available. To help address the issue I created a function to automate the process. Keep in mind this function should only be used to delete an agent hosted by a computer that no longer exists otherwise you should use Uninstall-Agent.
# Summary
# Delete an agent hosted by a non-existent computer.
# Params
# AgentNames - An array of strings that contain the FQDN of agents to delete.
# Returns
# None
function global:Delete-Agent([System.String[]] $agentNames)
{
$NoAgentsErrorMsg = "`nNo agent names specified. Please specify the FQDN for each agent you want to delete.`n";if ($agentNames -eq $null)
{
Write-Host $NoAgentsErrorMsg;
return;
}$administration = (get-item .).ManagementGroup.GetAdministration();
$agentManagedComputerType = [Microsoft.EnterpriseManagement.Administration.AgentManagedComputer];
$genericListType = [System.Collections.Generic.List``1]
$genericList = $genericListType.MakeGenericType($agentManagedComputerType)$agentList = new-object $genericList.FullName
foreach ($agentName in $agentNames)
{
$agent = Get-Agent | where {$_.PrincipalName -eq $agentName}
if ($agent -eq $null)
{
$msg = "Agent '{0}' not found." -f $agentName;
Write-Host $msg;}
else
{
$agentList.Add($agent);
}
}if ($agentList.Count -eq 0)
{
Write-Host $NoAgentsErrorMsg;
return;
}$genericReadOnlyCollectionType = [System.Collections.ObjectModel.ReadOnlyCollection``1]
$genericReadOnlyCollection = $genericReadOnlyCollectionType.MakeGenericType($agentManagedComputerType)$agentReadOnlyCollection = new-object $genericReadOnlyCollection.FullName @(,$agentList);
$msg = "`nDeleting {0} agents:`n" -f $agentReadOnlyCollection.Count;
Write-Host $msg;
foreach ($agent in $agentReadOnlyCollection)
{
Write-Host $agent.PrincipalName;
}
$administration.DeleteAgentManagedComputers($agentReadOnlyCollection);
}
Hope that helps and as always please post your questions and comments and I will make sure they are addressed in future posts.
Roger Sprague