Private/Remove-AGLowPrivUser.ps1

function Remove-AGLowPrivUser {
    <#
    .SYNOPSIS
        Deletes the low privileged lab user, but only if ADCSGoat created it.
 
    .DESCRIPTION
        Internal helper. A user whose description lacks the ADCSGoat marker is
        left alone with a warning.
 
    .PARAMETER UserName
        The sAMAccountName of the user.
 
    .PARAMETER Server
        The domain controller to write to.
 
    .OUTPUTS
        System.Boolean. $true when the user was deleted.
 
    .EXAMPLE
        Remove-AGLowPrivUser -UserName user -Server dc.adcs.goat
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([bool])]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$UserName,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Server
    )

    Add-Type -AssemblyName System.DirectoryServices

    $serverPrefix = if ($Server) { "LDAP://$Server/" } else { 'LDAP://' }
    $rootDSE = New-Object System.DirectoryServices.DirectoryEntry("${serverPrefix}RootDSE")
    $defaultNC = "$($rootDSE.defaultNamingContext)"

    $searcher = New-Object System.DirectoryServices.DirectorySearcher
    $searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry("$serverPrefix$defaultNC")
    $searcher.Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=$UserName))"
    $null = $searcher.PropertiesToLoad.Add('description')
    $result = $searcher.FindOne()
    if ($null -eq $result) { return $false }

    if ("$($result.Properties['description'][0])" -notlike '*Generated by ADCSGoat*') {
        Write-Warning "User '$UserName' was not created by ADCSGoat; leaving it in place."
        return $false
    }

    if (-not $PSCmdlet.ShouldProcess($UserName, 'Delete low privileged domain user')) { return $false }

    $user = $result.GetDirectoryEntry()
    $user.DeleteTree()
    $true
}