Disable user script check

by Jan 26, 2015

Created a script that can be used to quickly disable a user. But can someone check the script and give me advice on how to improve the script? There's always room for improvement 🙂

function Disable-User{
    
    [CmdletBinding(DefaultParameterSetName="Default")]
      Param(
        [Parameter(Mandatory=$True,Position=0,HelpMessage="Enter the username.")]
        [String]$User,
        [Parameter(Mandatory=$False,Position=1,ParameterSetName="MailboxAccess",HelpMessage="Enter the username requiring access to the user's mailbox.")]
        [Object[]]$GrantMailboxAccessTo   
           )

# Force en-US settings, IMPORTANT when using different regional settings
[Threading.Thread]:: CurrentThread.CurrentCulture = 'en-US'

#Enter in administrator credentials
$cred = Get-Credential -Credential $runuser

#Load ActiveDirectory Module
If (!(Get-module ActiveDirectory )) 
{
    write-host "Loading Active Directory modules" -foregroundcolor "green"
    Import-Module ActiveDirectory
}

#Variables Exchange Server
$ExchangeServer = "ExchangeServer/.../"

#Load assembly to show message box
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | out-null

    #Prompt for confirmation of user account removal
    if([System.Windows.Forms.MessageBox]::Show("Disable account " + $user + " and remove from all groups?", "Question",[System.Windows.Forms.MessageBoxButtons]::YesNo) -eq "Yes")
    {
        cls
"**************************************"
"*           Select the OU            *"    
"*            1) 30 days OU           *"
"*            2) 60 days OU           *"
"*            3) 90 days OU           *"
"*            4) Do not delete OU     *"
"**************************************"
$a=read-host
IF ($a -eq '1') {
write-host "Moved $user to the Delete 30 days OU" -ForegroundColor Green
get-aduser $user | move-adobject -targetpath "OU=Delete 30 Days,OU=Disabled Users,DC=Domain,DC=com" 
$ou = "30 days OU"
 }

ElseIf ($a -eq '2') {
write-host "Moved $user to the Delete 60 days OU" -ForegroundColor Green
get-aduser $user | move-adobject -targetpath "OU=Delete 60 Days,OU=Disabled Users,DC=Domain,DC=com" 
$ou = "60 days OU"
}

ElseIf ($a -eq '3') {
write-host "Moving $user to the Delete 90 days OU" -ForegroundColor Green
get-aduser $user | move-adobject -targetpath "OU=Delete 90 Days,OU=Disabled Users,DC=Domain,DC=com" 
$ou = "90 days OU"
}

ElseIf ($a -eq '4') {
write-host "Moving $user to the Do not delete" -ForegroundColor Green
get-aduser $user | move-adobject -targetpath "OU=Do not delete,OU=Disabled Users,DC=Domain,DC=com" 
$ou = "Do not delete OU"
}

#Disable user
        $Disabled = Get-Aduser $user
        If ($Disabled.enabled -eq $true)
        {
            Disable-ADAccount -Identity $user 
            write-host "$user account has been disabled" -foregroundcolor Green
        }

#Change Description"
        $DisabledBy = $env:username
        $Date = get-date -uformat "%d-%m-%Y"
        $UserDescription = "Disabled-" + "$Date" +  "-"  + "$DisabledBy"
        set-ADUser $user -Description "$UserDescription" 
        write-host "$user description set to $UserDescription" -foregroundcolor green

#Removes group membership from disabled users
write-host "Removing group memberships." -ForegroundColor Green
       $groups = Get-ADuser $User -Properties memberof | select -ExpandProperty memberof
            $groups | Remove-ADGroupMember -members $User -ErrorAction SilentlyContinue -confirm:$False 

#Start implicit remoting session Exchange server
Write-host "Starting remote session with $ExchangeServer." -ForegroundColor Green
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchangeServer -Authentication Kerberos -Credential $cred
Import-PSSession $s -AllowClobber -DisableNameChecking

#Hide user from GAL
write-host "Hiding $user from Global Address List" -ForegroundColor Green
Set-Mailbox -Identity $user -HiddenFromAddressListsEnabled $true 

#Removing forwards
write-host "Removing forwarders to external addresses" -ForegroundColor Green
Get-InboxRule -mailbox $user -ErrorAction:SilentlyContinue | Where-Object {$_.ForwardTo -ne $null -and $_.ForwardTo -Notlike "*EmailDomain*"} | remove-inboxrule -confirm:$False 
#Remove redirects to external email addresses write-host "Deleting redirects to external email adresses" Get-InboxRule -Mailbox $user -ErrorAction:SilentlyContinue | Where-Object {$_.RedirectTo -ne $null -and $_.RedirectTo -Notlike "*EX:/o=EmailDomain*"} | remove-inboxrule -confirm:$False #Remove Activesync Access IF (Get-CASMailbox $user | where-object {$_.ActiveSyncEnabled -eq $true}) { Set-CASMailbox -Identity $user -ActiveSyncEnabled $false write-host "Disabled Activesync" -foregroundcolor green } else { write-host "Activesync already disabled for $user" -foregroundcolor green } #Set mailbox access If($PSCmdlet.ParameterSetName -eq "MailboxAccess"){ $user1 = get-aduser $user -Properties * If($GrantMailboxAccessTo -ne $null){ Foreach ($GrantMailboxAccess in $GrantMailboxAccessTo){ $GrantMailboxAccess1 = get-aduser $GrantMailboxAccess -Properties * Add-ADPermission -Identity $user1.DistinguishedName -User $GrantMailboxAccess1.SamAccountName -ExtendedRights 'Send-as' -ErrorAction Stop Write-host "$($GrantMailboxAccess1.name) has been granted Send-As access to $($User1.name)'s mailbox." Add-MailboxPermission -Identity $User1.DistinguishedName -User $GrantMailboxAccess1.SamAccountName -AccessRights 'FullAccess' Write-host "$($GrantMailboxAccess1.name) has been granted Full Access access to $($User1.name)'s mailbox." } } } #Closing current pssessions write-host "Closing remote pssession" -ForegroundColor Green get-pssession | Remove-PSSession #Create new object for logging $date = get-date $obj = New-Object PSObject $obj | Add-Member -MemberType NoteProperty -Name "Name" -Value $User $obj | Add-Member -MemberType NoteProperty -Name "Status" -Value 'Disabled' $obj | Add-Member -MemberType NoteProperty -Name "Date" -Value "$date" $obj | Add-Member -MemberType NoteProperty -Name "OU" -Value "$ou" $obj | Add-Member -MemberType NoteProperty -Name "Disabled by" -Value "$DisabledBy" #Adds object to the log array $LogArray += $obj #Exports log array to CSV file in the temp directory with a date and time stamp in the file name. write-host "exporting CSV file" $logArray | Export-Csv "\FileShareDisabled_Users.csv" -NoTypeInformation -Append } #Exit script else { write-warning "No Changes Made" } }