Functions/Remove-SCOMAgentManagementGroup.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

<#
    .SYNOPSIS
    Remove an existing Management Group connection from a SCOM Agent.

    .DESCRIPTION
    Use PowerShell Remoting in combination with a local COM object query to
    remove an existing Management Group from the SCOM Agent.

    .INPUTS
    None.

    .OUTPUTS
    None.

    .EXAMPLE
    PS C:\> Remove-SCOMAgentManagementGroup -ComputerName 'PC1' -ManagementGroupName 'CONTOSO'
    Remove the CONTOSO Managemeng Group from the SCOM Agent PC1.

    .NOTES
    Author : Claudio Spizzi
    License : MIT License

    .LINK
    https://github.com/claudiospizzi/OperationsManagerFever
#>


function Remove-SCOMAgentManagementGroup
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        # Management group name.
        [Parameter(Mandatory = $true)]
        [System.String]
        $ManagementGroupName,

        # Computer name of the target agent.
        [Parameter(Mandatory = $false)]
        [System.String[]]
        $ComputerName = 'localhost',

        # Optional credentials to perform the action.
        [Parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = $null
    )

    begin
    {
        # Optional credential parameter
        $credentialParam = @{}
        if ($Credential -ne $null)
        {
            $credentialParam['Credential'] = $Credential
        }

        # Query script block
        $query = {

            param ($ManagementGroupName)

            try
            {
                $config = New-Object -ComObject AgentConfigManager.MgmtSvcCfg
            }
            catch
            {
                throw "No Monitoring Agent installed on $Env:ComputerName."
            }

            $groups = $config.GetManagementGroups() | Select-Object -ExpandProperty 'managementGroupName'

            if ($groups -contains $ManagementGroupName)
            {
                $config.RemoveManagementGroup($ManagementGroupName)
            }
            else
            {
                throw "Management Group $ManagementGroupName not found on Monitoring Agent $Env:ComputerName."
            }
        }
    }

    process
    {
        foreach ($computer in $ComputerName)
        {
            if ($PSCmdlet.ShouldProcess($computer, "Remove Management Group $ManagementGroupName"))
            {
                Invoke-Command -ComputerName $ComputerName -ScriptBlock $query -ArgumentList $ManagementGroupName @credentialParam -ErrorAction Continue
            }
        }
    }
}