change SCOM agent assignement to other SCOM gateway

if you need to change the assignement of a SCOM gateway to another SCOM gateway, you can do this by this script:

<#
    .SYNOPSIS
        This script sets a new Management Point for a SCOM Agent

    .PARAMETER ManagementPoint
        defines the Management Point or Gateway to use

    .PARAMETER ManagementGroup
        defines the Management Group to use

    .EXAMPLE
        Set-ScomManagementPoint.ps1 -ManagementPoint 'gateway.domain.net' -ManagementGroup 'MG001'
#>
Param (
    [string]$ManagementPoint
    ,
    [string]$ManagementGroup = 'MG001'
)
try {
    $SCOMAgent = New-Object -ComObject AgentConfigManager.MgmtSvcCfg
}
catch {
    Write-Output "no SCOM Agent found"
}
if ( -not ( [string]::IsNullOrEmpty( $SCOMAgent ) ) ) {
    Stop-Service -Name HealthService

    $StateDirectory = Get-ItemPropertyValue -Path HKLM:\SYSTEM\CurrentControlSet\services\HealthService\Parameters -Name 'State Directory'

    $CurrentMGs = $SCOMAgent.GetManagementGroups()
    foreach ( $CurrentMG in $CurrentMGs ) {
        try {
            $SCOMAgent.RemoveManagementGroup( $CurrentMG.managementGroupName )
        }
        catch {
            throw "couldn't remove current Management Group '$( $CurrentMG.managementGroupName )'"
        }
    }

    $ChildItems = Get-ChildItem -Path $StateDirectory
    foreach ( $ChildItem in $ChildItems ){
        try {
            Remove-Item -Recurse -Force -Confirm:$false -Path $ChildItem.FullName
        }
        catch {
            throw "couldn't remove '$( $ChildItem.FullName )'"
        }
    }

    $SCOMAgent.AddManagementGroup($ManagementGroup, $ManagementPoint, 5723)

    $SCOMAgent.ReloadConfiguration()

    $MGs = $SCOMAgent.GetManagementGroups()
    foreach ( $MG in $MGs ) {
        Write-Output "$( $MG.managementGroupName ):$( $MG.ManagementServer )"
    }
}

please note, that this script will remove the old assignement and clean up the state directory. if you don’t cleanup the state directory, the agent will after a service restart be assigned again to the old gateway.