GinShell.Windows/Public/Remove-GsDomain.ps1

function Remove-GsDomain {
    <#
    .SYNOPSIS
        Removes the local machine from its Active Directory domain.
    .PARAMETER Credential
        PSCredential with permission to unjoin the domain.
    .PARAMETER WorkgroupName
        Workgroup to join after leaving the domain. Default: WORKGROUP.
    .PARAMETER NewComputerName
        Optionally rename the computer after unjoining.
    .PARAMETER Restart
        Restart the computer after unjoining.
    .EXAMPLE
        $cred = Get-Credential
        Remove-GsDomain -Credential $cred -Restart
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]$Credential,

        [string]$WorkgroupName = 'WORKGROUP',

        [string]$NewComputerName = $env:COMPUTERNAME,

        [switch]$Restart
    )

    try {
        Write-GsLog -Message "Preparing to remove domain and join workgroup '$WorkgroupName'..." -Type Info

        if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Unjoin domain and join '$WorkgroupName'")) {
            Remove-Computer -UnjoinDomainCredential $Credential -WorkgroupName $WorkgroupName -PassThru -Verbose -Force -Restart:$false -ErrorAction Stop
            Write-GsLog -Message "Successfully removed from domain and joined workgroup '$WorkgroupName'." -Type Success

            if ($NewComputerName -ne $env:COMPUTERNAME) {
                Rename-Computer -NewName $NewComputerName -Force -Restart:$false -ErrorAction Stop
                Write-GsLog -Message "Computer renamed to '$NewComputerName'." -Type Success
            }

            if ($Restart) {
                Write-GsLog -Message "Restarting computer..." -Type Info
                Restart-Computer -Force
            }
        }
    }
    catch {
        Write-GsLog -Message "Failed to remove domain: $_" -Type Error
        throw
    }
}