Created
May 26, 2012 00:55
-
-
Save theagreeablecow/2791536 to your computer and use it in GitHub Desktop.
Disable a user is AD, Exchange and Lync
This file contains 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
# This script manages the process for a departing user, using data retrived from a CSV file | |
# Requires the Active Directory module for Windows Powershell and appropriate credentials | |
# CSV file with corresponding header and user(s) info: | |
# UserName,DisableWindows,ArchiveFiles,DisableVoice,ArchiveMailbox,MailboxAccessTo,DisableEmailAddress,AutoReplyContact,ReminderInDays | |
#LOAD POWERSHELL SESSIONS | |
#------------------------ | |
$exchangeserver = "exchange1.MyDomain.com.au" | |
$Lyncserver = "lync1.MyDomain.com.au" | |
$DC = "dc1.MyDomain.com.au" | |
$usercredential= get-credential -credential MyDomain\admin | |
cls | |
write-host -foregroundcolor Green "Loading modules for AD, Exchange and Lync..." | |
$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$exchangeserver/PowerShell/ -Authentication Kerberos -Credential $UserCredential | |
Import-PsSession $exchangesession | |
$lyncsession = new-pssession -connectionuri https://$Lyncserver/ocspowershell -credential $usercredential | |
Import-PSSession $lyncsession | |
import-module ActiveDirectory | |
#UPDATE USER DATA ON CSV FILE | |
#---------------------------- | |
$InputPath = "\\MyDomain.com.au\Scripts\Data\" | |
$InputFile = $InputPath + "DepartingUserInfo.csv" | |
Invoke-Item $inputFile | |
cls | |
write-host -foregroundcolor Green "Update user details and save CSV file. Press any key to continue" | |
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | |
#DEFINE VARIABLES | |
#---------------- | |
$inputFile = Import-CSV $inputFile | |
$MailArchiveDB = "ArchiveDB1" | |
$ArchiveOU = "OU=zzz_ARCHIVE,DC=MyDomain,DC=com,DC=au" | |
$HelpdeskEmail = "[email protected]" | |
$ExtraEmail = "[email protected]" | |
$AdminEmail = "[email protected]" | |
$ScriptUser = $env:username | |
foreach($line in $inputFile) | |
{ | |
#Retrieve details from CSV file | |
$Username = $line.UserName # sAMAccountName | |
$DisableWindows = $line.DisableWindows # yes or no | |
$ArchiveFiles = $line.ArchiveFiles # yes or no | |
$DisableVoice = $line.DisableVoice # yes or no | |
$ArchiveMailbox = $line.ArchiveMailbox # yes or no | |
$EmailManager = $line.MailboxAccessTo # sAMAccountName | |
$DisableEmail = $line.DisableEmailAddress # yes or no | |
$EmailReply = $line.AutoReplyContact # sAMAccountName | |
$Reminder = $line.ReminderInDays # eg 30 | |
$LogFile = $InputPath+"DisableLog_" +$username +".txt" | |
#Validation | |
if ($DisableEmail -eq "no" -And $EmailReply -eq "") {$EmailReply = read-host -prompt "Email is not being disabled. You must enter a valid username for AutoReply contact details"} | |
if ($DisableEmail -eq "no" -And $Reminder -eq "") {$Reminder = read-host -prompt "Email is not being disabled. You must enter number of days for a reminder"} | |
#Get User Details | |
$UserDetails = Get-ADUser $username -Server $DC -properties Office,DisplayName,Mail,distinguishedName | select-object Office,DisplayName,Mail,distinguishedName | |
$UserOffice = $UserDetails.Office | |
$UserDisplayName = $UserDetails.DisplayName | |
$UserEmail = $UserDetails.Mail | |
$UserDN = $UserDetails.distinguishedName | |
#Get Details of Person Managing Emails | |
$ManagerDetails = Get-ADUser $EmailManager -Server $DC -properties DisplayName,Mail | select-object DisplayName,Mail | |
$ManagerName = $ManagerDetails.DisplayName | |
$ManagerEmail = $ManagerDetails.Mail | |
#Get Details for Auto-Reply Message | |
$EmailReplyDetails = Get-ADUser $EmailReply -Server $DC -properties DisplayName,OfficePhone,Mail | select-object DisplayName,OfficePhone,Mail | |
$EmailReplyName = $EmailReplyDetails.DisplayName | |
$EmailReplyPhone = $EmailReplyDetails.OfficePhone | |
$EmailReplyEmail = $EmailReplyDetails.Mail | |
#Get Script User's Details | |
$ScriptUserDetails = Get-ADUser $ScriptUser -Server $DC -properties mail | select-object mail | |
$ScriptUserEmail = $ScriptUserDetails.mail | |
#Retrieve Site Specific Variables | |
if ($UserOffice -eq "City1") | |
{ | |
$ProfilePath = "\\server1\profiles\" +$username | |
$ProfileArchive = "\\archive1\Users\Profiles\" | |
$HomePath = "\\server1\home$\" +$username | |
$HomeArchive = "\\archive1\Users\Home\" | |
$Reception = "(+61) 3 1234 1234" | |
} | |
elseif ($UserOffice -eq "City2") | |
{ | |
$ProfilePath = "\\server2\profiles\" +$username | |
$ProfileArchive = "\\archive2\Users\Profiles\" | |
$HomePath = "\\server2\home$\" +$username | |
$HomeArchive = "\\archive2\Users\Home\" | |
$Reception = "(+61) 3 1234 1234" | |
} | |
elseif ($UserOffice -eq "City3") | |
{ | |
$ProfilePath = "\\server3\profiles\" +$username | |
$ProfileArchive = "\\archive3\Users\Profiles\" | |
$HomePath = "\\server3\home$\" +$username | |
$HomeArchive = "\\archive3\Users\Home\" | |
$Reception = "(+61) 3 1234 1234" | |
} | |
elseif ($UserOffice -eq "City4") | |
{ | |
$ProfilePath = "\\server4\profiles\" +$username | |
$ProfileArchive = "\\archive4\Users\Profiles\" | |
$HomePath = "\\server4\home$\" +$username | |
$HomeArchive = "\\archive4\Users\Home\" | |
$Reception = "(+61) 3 1234 1234" | |
} | |
else | |
{ | |
write-host -foregroundcolor Red "Error: Office '" $UserOffice "' not recognised." | |
exit | |
} | |
#Enable Logging | |
Start-Transcript -path $LogFile -append | |
$now = (Get-Date) | |
write-host -foregroundcolor Green "Starting disable procedure for" $UserDisplayName $now | |
#Archive Files | |
#------------- | |
# Ensure you have full access permission to all directories | |
$ArchiveFiles = $ArchiveFiles.ToLower() | |
if ($ArchiveFiles -eq "yes") | |
{ | |
write-host -foregroundcolor Green "Archiving Profile and Home Directories" | |
#Archive Profile Directory | |
$win7Profile = $ProfilePath +".V2" | |
IF (TEST-PATH $win7Profile) | |
{ | |
Copy-Item -Recurse $win7Profile $ProfileArchive -force | |
Remove-Item -Recurse $win7Profile | |
} | |
IF (TEST-PATH $ProfilePath) | |
{ | |
Copy-Item -Recurse $ProfilePath $ProfileArchive -force | |
Remove-Item -Recurse $ProfilePath | |
} | |
#Archive Home Directory | |
IF (TEST-PATH $HomePath) | |
{ | |
Copy-Item -Recurse $HomePath $HomeArchive -force | |
Remove-Item -Recurse $HomePath | |
} | |
} | |
#Disable Enterprise Voice | |
#------------------------ | |
$DisableVoice = $DisableVoice.ToLower() | |
if ($DisableVoice -eq "yes") | |
{ | |
#Remove Unified Messaging from Exchange | |
write-host -foregroundcolor Green "Removing unified messaging from Exchange" | |
Get-Mailbox $username -DomainController $DC | Disable-UMMailbox -DomainController $DC -confirm:$false | |
#Remove User from Lync | |
write-host -foregroundcolor Green "Removing user from Lync" | |
Disable-CsUser $username -DomainController $DC | |
} | |
# Update Mailbox Permissions | |
#--------------------------- | |
if (!($EmailManager -eq $NULL)) | |
{ | |
write-host -foregroundcolor Green "Granting mailbox permissions to" $ManagerName | |
Add-MailboxPermission -Identity $username -User $EmailManager -AccessRights 'FullAccess' | |
#Send message to Email Manager advising changes. | |
$MailSubject = "[AUTO] Mailbox Access Granted for " +$UserDisplayName | |
$MailBody = "FYI: " +$UserDisplayName +"'s account has now been disabled. You have been granted full access to manage their mailbox. `r | |
Please contact Helpdesk ("+$HelpdeskEmail+") if you need any assistance with access or to make any changes.`r | |
Regards`r | |
Admin Scripts" | |
Send-MailMessage -To $ManagerEmail -From $HelpdeskEmail -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody | |
#Optional: Send message to SOMEONE asking them to do SOMETHING | |
$MailSubject = "[AUTO] Please do something regarding " +$UserDisplayName | |
$MailBody = $UserDisplayName +" has left the company. Please do something. Any queestions please ask " +$ManagerName | |
Send-MailMessage -To $DBAEmail -From $HelpdeskEmail -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody | |
} | |
#Update Auto Reply and set a Reminder or just Disable Email address now | |
#---------------------------------------------------------------------- | |
$DisableEmail = $DisableEmail.ToLower() | |
if ($DisableEmail -eq "no") | |
{ | |
#Add Auto Reply to mailbox (with contact details) | |
write-host -foregroundcolor Green "Creating an AutoReply message with contact details for" $EmailReplyName | |
if ($EmailReplyEmail -eq "") {$EmailReplyEmail = read-host -prompt "Please add an EMAIL ADDRESS for " +EmailReplyName} | |
#if ($EmailReplyPhone -eq "") {$EmailReplyPhone = read-host -prompt "Please add a PHONE NUMBER for " +EmailReplyName} | |
$Message = $UserDisplayName + " is no longer employed with MyCompany. Please refer all queries to " + $EmailReplyName + " at " + $EmailReplyEmail + " or by phone on " + $Reception +"." | |
Set-MailboxAutoReplyConfiguration -AutoReplyState Enabled -Identity $Username -InternalMessage $Message -ExternalMessage $Message | |
#Send message to AutoReply contact advsing changes | |
$MailSubject = "[AUTO] AutoReply updated for " +$UserDisplayName | |
$MailBody = "FYI: "+$UserDisplayName+"'s account has now been disabled. You have been nominated as a contact in their 'Out of Office' message, which reads as follows: `r | |
"+$Message+" `r | |
Please contact Helpdesk ("+$HelpdeskEmail+") if you need to make any changes.`r | |
Regards`r | |
Admin Scripts" | |
Send-MailMessage -To $EmailReplyEmail -From $HelpdeskEmail -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody | |
#Add Calendar Reminder (current user), to disable email in future | |
write-host -foregroundcolor Green "Adding celendar reminder to disable email in" $Reminder "days" | |
$outlook = New-Object -ComObject Outlook.Application | |
$entry = $Outlook.Application.CreateItem(1) | |
$Start = (Get-Date).AddDays($Reminder) | |
$End = $start.AddMinutes(15) | |
$Subject = "Disable email address for " +$UserDisplayName | |
$Location = $UserOffice | |
$Body = $UserDisplayName +" left the company " +$Reminder +" days ago. It is now time to disable the email address. Using Exchange, change the primary SMTP address to " +$UserEmail +".DISABLED and remove any additional addresses" | |
$entry.Start = $Start | |
$entry.End = $End | |
$entry.Subject = $Subject | |
$entry.Location = $Location | |
$entry.Body = $Body | |
$entry.Save() | |
} | |
else | |
{ | |
#Rename Email address in Exchange ([email protected]) | |
write-host -foregroundcolor Green "Disabling email address" | |
Set-Mailbox -identity $username -EmailAddressPolicyEnabled $false | |
$DisabledEmail = "SMTP:" +$UserEmail +".DISABLED" | |
Set-Mailbox -identity $username -EmailAddresses $DisabledEmail | |
} | |
#Archive Mailbox | |
#--------------- | |
$ArchiveMailbox = $ArchiveMailbox.ToLower() | |
if ($ArchiveMailbox -eq "yes") | |
{ | |
#Remove from Address Book | |
write-host -foregroundcolor Green "Removing user from Global Address Book" | |
Set-Mailbox -identity $username -HiddenFromAddressListsEnabled $true | |
#Move Mailbox to Archive Data Base | |
write-host -foregroundcolor Green "Moving mailbox to archive database" | |
New-MoveRequest -identity $username -TargetDatabase $MailArchiveDB | |
} | |
#Disable AD Accounts | |
#------------------- | |
$DisableWindows = $DisableWindows.ToLower() | |
if ($DisableWindows -eq "yes") | |
{ | |
write-host -foregroundcolor Green "Disabling user account and removing details from Active Directory" | |
#Remove from Intranet | |
# Sharepoint = auto?? | |
#Move user object to Archive OU | |
Move-ADObject -Identity $UserDN -TargetPath $ArchiveOU | |
#Remove AD Deatails | |
Set-ADUser $username -Server $DC -Clear Manager | |
Set-ADUser $username -Server $DC -Clear TelephoneNumber | |
Set-ADUser $username -Server $DC -Clear IpPhone | |
Set-ADUser $username -Server $DC -Clear ProfilePath | |
Set-ADUser $username -Server $DC -Replace @{description="**ACCOUNT DISABLED**"} | |
#Remove from Groups | |
$ds = new-object directoryServices.directorySearcher | |
$ds.filter = "(&(objectCategory=person)(objectClass=user)(samAccountName="+$username+"))" | |
$dn = $ds.findOne() | |
$user = [ADSI]$dn.path | |
foreach ($group in $user.memberof) | |
{ | |
Remove-ADGroupMember -Identity $group -Members $username -Confirm:$false | |
$RPTGroups = $RPTGroups +" " + $group | |
} | |
write-host $UserDisplayName "has been removed from the following groups:" $RPTGroups | |
write-host "`r" | |
#Reset User Password | |
$prompt = "Please enter new password for " +$UserDisplayName | |
$accountpassword = read-host -assecurestring -prompt $prompt | |
Set-ADAccountPassword $username -Server $DC -Reset -NewPassword $accountpassword | |
#Disable AD Account | |
Disable-ADAccount $username -Server $DC | |
} | |
#Send Reports | |
#------------- | |
#Helpdesk/Admin - summarise change in email, plus include | |
write-host -foregroundcolor Green "Disable procedure completed. Sending you a wrap up email with log file." | |
Stop-Transcript | |
#Email IT report | |
$MailSubject = "[AUTO] Account disabled for " +$UserDisplayName | |
$MailBody = "The user account has been disabled for " +$UserDisplayName+", on "+(get-date)+". See attached log for details. `r | |
Please ensure to complete the following items: `r | |
- Manual Step 1 `r | |
- Manual Step 2 `r | |
- Manual Step 3 `r | |
Regards`r | |
Admin Scripts" | |
Send-MailMessage -To $ScriptUserEmail -cc $AdminEmail -From "[email protected]" -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody -attachment $LogFile | |
#Pause for review, then load next line | |
write-host "`r" | |
write-host -foregroundcolor Green "User disabled. Press any key to continue" | |
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | |
} | |
exit | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment