aboutsummaryrefslogtreecommitdiff
path: root/Disable-MachineAccount.ps1
blob: ad68cbb9be66e8e91ad7fd7bee86772d3b42f123 (plain)
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
98
99
function Disable-MachineAccount
{
    <#
    .SYNOPSIS
    This function disables a machine account added with New-MachineAccount. This function should be used with the same
    user that created the machine account.

    Author: Kevin Robertson (@kevin_robertson)  
    License: BSD 3-Clause 
    
    .DESCRIPTION
    Machine accounts added with New-MachineAccount cannot be deleted with an unprivileged user. Although users
    can remove systems from a domain that they added using ms-DS-MachineAccountQuota, the machine account in AD is
    just left in a disabled state. This function provides that ability. Ideally cleanup is performed after
    elevating privilege.

    Note that this function does not accept credentials.

    .PARAMETER DistinguishedName
    Distinguished name for the computers OU.

    .PARAMETER Domain
    The targeted domain.

    .PARAMETER MachineAccount
    The username of the machine account that will be disabled.

    .EXAMPLE
    Disable-MachineAccount -MachineAccount iamapc

    .LINK
    https://github.com/Kevin-Robertson/Powermad
    #>

    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$false)][String]$DistinguishedName,
        [parameter(Mandatory=$false)][String]$Domain,
        [parameter(Mandatory=$true)][String]$MachineAccount
    )

    if($MachineAccount.EndsWith('$'))
    {
        $machine_account = $MachineAccount.SubString(0,$MachineAccount.Length - 1)
    }
    else
    {
        $machine_account = $MachineAccount  
    }

    if(!$Domain)
    {
        $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
    }

    if(!$DistinguishedName)
    {

        $distinguished_name = "CN=$machine_account,CN=Computers"

        $DCArray = $Domain.Split(".")

        ForEach($DC in $DCArray)
        {
            $distinguished_name += ",DC=$DC"
        }

    }
    else 
    {
        $distinguished_name = "$DistinguishedName"
    }

    $account = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$distinguished_name"

    if(!$account.InvokeGet("AccountDisabled"))
    {

        try 
        {
            $account.InvokeSet("AccountDisabled","True")
            $account.SetInfo()
            Write-Output "[+] $machine_account has been disabled"
        }
        catch
        {
            $error_message = $_.Exception.Message
            $error_message = $error_message -replace "`n",""
            Write-Output "[-] $error_message"
        }

    }
    else
    {
        Write-Output "[-] $machine_account is already disabled"   
    }
    
}