Wednesday 20 November 2013

Microsoft: Disable User's Account, Remove All The Membership and Add The User to A Distribution Group in Active Directory

The Powershell script below allows you to disable an user's account, remove all his/her membership and add him/her to a distribution group for easy account management. This script helps when an user checks out from a company / resign.


# User Disable Script
# Author: Andres Cheah
# NOTE: This script allows you to disable an user's account, remove all his/her membership and add him/her to DisableMailbox group.
#

Import-Module ActiveDirectory
add-PSSnapin  quest.activeroles.admanagement -ErrorAction SilentlyContinue -WarningAction SilentlyContinue

function Get-DNC
{
Param (
    $RDSE
    )
 
    $DomainDNC = $RDSE.defaultNamingContext
    Return $DomainDNC

}
$NC = (Get-DNC([adsi]("LDAP://RootDSE")))

function get-dn ($SAMName)
{
  $root = [ADSI]''
  $searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))"
$user = $searcher.findall()

if ($user.count -gt 1)
      {  
            $count = 0
            foreach($i in $user)
            {
write-host $count ": " $i.path
                  $count = $count + 1
            }

            $selection = Read-Host "Please select item: "
return $user[$selection].path

      }
      else
      {
  return $user[0].path
      }
}


function programEX(){

CLS
Write-Host "******************************************************"
Write-Host "* User Disable Script"
Write-Host "* Author: Andres Cheah"
Write-Host "* NOTE: This script allows you to disable an user's"
Write-Host "* account, remove all his/her membership and add"
Write-Host "* him/her to DisableMailbox group."
Write-Host "******************************************************"
Write-Host ""
[console]::ForegroundColor = "yellow"
[console]::BackgroundColor= "black"
$Name = Read-Host "Please enter the username you wish to disable"
[console]::ResetColor()
$status = "disable"
$path = get-dn $Name
"'" + $path + "'"

$QADPath = Get-QADUser -Identity $Name

if ($status -match "disable")
{
# Disable the account
$account=[ADSI]$path
$account.psbase.invokeset("AccountDisabled", "True")
$account.setinfo()
}

[console]::ForegroundColor = "cyan"
[console]::BackgroundColor= "black"
$Reason = Read-Host "Please enter a description"
[console]::ResetColor()

Set-QADUser -Identity $Name -Description "$Reason"
Get-ADPrincipalGroupMembership -Identity $Name | % {Remove-ADPrincipalGroupMembership -Identity $Name -MemberOf $_}
Add-ADPrincipalGroupMembership -identity $Name -Memberof "Domain Users","DisableMailbox"
Write-Host ""
Write-Host "The user has been disabled and moved." -ForegroundColor "Red"
Write-Host ""

$Choice = Read-Host "Would you like to disable another account? [y]"
If ($Choice.ToLower() -eq "y"){
programEX
}else{
exit
}
}
programEX

No comments:

Post a Comment