Moving Agents using PowerShell

We recently had a situation where we needed to move agents from one management server to another. Actually we needed to remove all agents from 2 Management Servers truth be told…but soon after we moved them, we needed to move them back… the trouble is – how do we know which Agents were originally from server 1 and which were from server 2?

Rather than do it the hard, old fashioned way (manually creating a list as there was over 1,000 agents on each Management Server)…I decided to do it the PowerShell way.

The first step was to get a list of all of the agents that were on Server 1.

get-agent | ? {$_.PrimaryManagementServerName -eq “server01.thescomlab.com”} | Select -expandproperty PrincipalName | Out-File C:\Temp\Servers.txt

Now that we have our list, we can move the agents to Server 2. We could use PowerShell for that, or we can do it even easier by selecting them in the SCOM Console and just moving them as a batch (as long as the servers are all on the same Management Server you can use the console easily).

Since the console method is a no-brainer, let’s do it via PowerShell.

$server02 = Get-ManagementServer | ? {$_.PrincipalName -eq “server02.thescomlab.com”}
foreach ($agent in (get-content “C:\Temp\Servers.txt”))
{
$currentagent = Get-agent | where {$_.PrincipalName -eq $agent}
Set-ManagementServer -PrimaryManagementServer $mon10 -AgentManagedComputer $currentagent
}

Now sit back and watch all of those agents being moved.
Once you’re ready to move them back, simply issue the same script in reverse.

$server01 = Get-ManagementServer | ? {$_.PrincipalName -eq “server01.thescomlab.com”}
foreach ($agent in (get-content “C:\Temp\Servers.txt”))
{
$currentagent = Get-agent | where {$_.PrincipalName -eq $agent}
Set-ManagementServer -PrimaryManagementServer $mon10 -AgentManagedComputer $currentagent
}

This will ensure that any Agents that were originally on Server02 will remain on Server02 and only those originally moved will return.

Advertisements
This entry was posted in Powershell for SCOM, SCOM Agents and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s