Created
August 4, 2016 23:08
-
-
Save zakes-it/5dbe57de8f80c59ee79918ca38d2677f to your computer and use it in GitHub Desktop.
Disable an Active Directory account, logging the group membership, stripping group membership and moving the account to a disabled users OU
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# turn down the AD account | |
Function Terminate-ADAccount { | |
[CmdletBinding()] | |
Param( | |
[System.Object[]]$user, | |
[System.Management.Automation.PSCredential]$cred, | |
[String]$DisabledOu, | |
[String]$MembershipLogPath | |
) | |
# Retrieve groups that the user is a member of | |
$Groups = Get-ADPrincipalGroupMembership $user.SamAccountName -credential $cred | |
if ( (($Groups).Count -le 1) -and ($user.DistinguishedName -match 'Disabled User Accounts') ) { | |
Write-Host "User account already disabled and stripped of groups." | |
Return "Skipped" | |
} | |
# Log the groups before removal. | |
$LogFilePath = $MembershipLogPath + $user.SamAccountName + "_" + $user.ObjectGUID.Guid + "_" + $(Get-Date -format M-d-yy-HHmm) + ".txt" | |
Out-File $LogFilePath -InputObject $Groups -Encoding utf8 | |
Write-Host "Group membership backed up to: $LogFilePath" -f green | |
# Disable the account | |
Disable-ADAccount $user.SamAccountName -cred $cred | |
if ( $? ) { | |
Write-Host "AD Account has been disabled." -f green | |
} else { | |
Write-Error "Failed to disable AD Account." | |
} | |
# Change the "group name" value and uncomment the following lines to change the user's primary AD group. | |
# Otherwise they will continue to have the default "Domain Users" group. | |
<# | |
Add-ADGroupMember "group name" $user.SamAccountName -cred $cred | |
$groupsid = (Get-ADGroup "group name").sid | |
[int]$primarygroupid = $groupsid.Value.Substring($groupsid.Value.LastIndexOf("-")+1 | |
Set-ADObject $user -Replace @{primaryGroupID="$GroupID"} -cred $cred | |
#> | |
# Strip group membership for the user for all but the primary group. | |
$Groups | ForEach-Object { | |
$CurrentGroup = $_ | |
try { | |
Remove-ADGroupMember -Identity $CurrentGroup -Members $user.SamAccountName -Confirm:$false -cred $cred | |
} catch { | |
Write-Host -f red ("Could not remove " + $user.Name + " from the following group: `"" + $CurrentGroup.name + "`"" ) | |
} | |
} | |
Write-Host "Account stripped of AD groups." -f green | |
# Move the user account to the disabled user account OU. | |
Move-ADObject $user.DistinguishedName -TargetPath $DisabledOu -credential $cred | |
Write-Host "Account moved to the disabled user account OU." -f green | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment