Public/Uninstall-ADCSGoat.ps1

function Uninstall-ADCSGoat {
    [CmdletBinding()]
    param (
        [switch]$Randomize
    )

    #region remove templates
    # Load the S.DS
    Add-Type -AssemblyName System.DirectoryServices

    # Get the Configuration partition automatically via RootDSE
    $RootDSE = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
    $ConfigurationPartition = $rootDSE.configurationNamingContext
    $TemplatesContainer = "CN=Certificate Templates,CN=Public Key Services,CN=Services,$ConfigurationPartition"
    $TemplatePath = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$TemplatesContainer")
    $AGTemplates = $TemplatePath.Children | Where-Object description -Like '*Generated by ADCSGoat*'

    # Delete each ADCSGoat template
    foreach ($template in $AGTemplates) {
        try {
            Write-Verbose "Attempting to delete template: $($template.Name)"
            $template.DeleteTree()
            Write-Verbose "Successfully deleted template: $($template.Name)"
        } catch {
            Write-Error "Failed to delete template $($Template.Name): $($_.Exception.Message)"
        }
    }

    # Clean up and dispose of the DirectoryEntry objects
    $TemplatePath.Dispose()

    #endregion remove issues

    #region ca issues
    # What: Get the list of all Enrollment Services, generate their full CA names, then add the name to the CA object
    # Why:
    $EnrollmentServices = Find-AGEnrollmentService
    $EnrollmentServices | Set-AGEnrollmentServiceFullName

    # What: Disable ESC5 configuration on all CAs.
    # Why:
    # $EnrollmentServices | ForEach-Object {
    # Write-Verbose "Granting Authenticated Users Full Control of: $($_.FullName)"
    # Enable-PCEditFlag -CAFullName $_.FullName -Flag EDITF_ATTRIBUTESUBJECTALTNAME2
    # }

    # What: Disable ESC6 configuration on all CAs.
    # Why:
    $EnrollmentServices | ForEach-Object {
        Write-Verbose "Assigning ESC6 configuration to: $($_.Name)"
        Disable-PCEditFlag -CAFullName $_.FullName -Flag EDITF_ATTRIBUTESUBJECTALTNAME2
    }

    # What: Disable ESC11 configuration on all CAs.
    # Why:
    $EnrollmentServices | ForEach-Object {
        Write-Verbose "Assigning ESC11 configuration to: $($_.Name)"
        Enable-PCInterfaceFlag -CAFullName $_.FullName -Flag IF_ENFORCEENCRYPTICERTREQUEST
    }

    #endregion ca issues
}