Public/Remove-ViewGroup.ps1

function Remove-ViewGroup {
<#
.SYNOPSIS
    Removes an existing View Group and all the views and groups present within that View Group
.DESCRIPTION
    Working with View Groups is not currently supported in MIP SDK, however the redistributable SDK
    includes an assembly containing the VmoClient which is a component used internally by the SDK
    and applications like XProtect Management Client.
 
    This function makes use of this VmoClient to manipulate the View Groups to enable complex tasks
    required in some environments.
.EXAMPLE
    PS C:\> Get-ViewGroup -Name 'Remote Guards' | Remove-ViewGroup
    Gets the View Group(s) named 'Remote Guards' and removes (deletes) them from the Management Server, including all views contained within.
#>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact='High')]
    param(
        # Specifies the View Group object to be deleted
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [VideoOS.Management.VmoClient.PublicViewGroup]
        $ViewGroup,
        # Specifies that all children of the Public View Group, including groups and views, should be removed as well
        [Parameter()]
        [switch]
        $Recurse
    )

    begin {
        $vmo = Get-VmoClient
    }

    process {
        try {
            if ($PSCmdlet.ShouldProcess("Public View Group '$($ViewGroup.Name)'", 'Remove')) {
                if ($Recurse) {
                    $stack = New-Object system.collections.generic.stack[VideoOS.Management.VmoClient.PublicViewGroup]
                    foreach ($group in $ViewGroup.PublicViewGroups) {
                        $stack.Push($group)
                    }
                    while ($stack.Count -gt 0) {
                        $group = $stack.Pop()
                        if ($group.PublicViewGroups.Count -gt 0) {
                            $stack.Push($group)
                            foreach ($subgroup in $group.PublicViewGroups) {
                                $stack.Push($subgroup)
                            }
                        }
                        else {
                            $views = $group.Views | Select-Object
                            foreach ($view in $views) {
                                $view.Delete()
                            }
                            $group.Delete()
                        }
                    }
                }
                if ($ViewGroup.PublicViewGroups.Count -gt 0) {
                    Write-Error "View Group '$($ViewGroup.Name)' contains child groups and/or views. Either delete these first, or include the Recurse switch."
                }
                else {
                    $ViewGroup.Delete()
                }
            }
        }
        catch {
            $vmo.Dispose()
            throw
        }
    }

    end {
        $vmo.Dispose()
    }
}