Disable an Exchange User without O365 with PowerShell



  • This script disables a users account by:

    • Asking a few questions
    • Changing the password
    • Forwarding their mail to their supervisor
    • Sending an email to HR & IT stating that the access has been revoked from that user

    This assumes that Exchange is on-premises.

    Import-Module activedirectory
    
    $un = Read-Host "Who are we disabling today? (Login Credentials)"
    $man = Read-Host "Who are we forwarding mail to? (Login Credentials)"
    $auth = Read-Host "Who are you? (Login Credentials)"
    
    #if ((Get-ADUser $auth -Properties memberof).memberof -match "Domain Admins"){
    #Resets the old user's password
    Set-ADAccountPassword -Identity $un -Reset -NewPassword (Read-Host -AsSecureString "Account Password")
    
    #Connects to the Exchange box, forwards the users email account to their supervisor/manager, then disconnects from the Exchange box
    $mail = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<Exchange>/powershell -name <Exchange> -Authentication Kerberos -Credential $cred
    Import-PSSession $mail -WarningAction SilentlyContinue | Out-Null
    Set-Mailbox $un -ForwardingAddress $man -RemovePicture #Sets the forwarding address to the manager and removes their picture
    Remove-PSSession -Session $mail #Disconnects from the Exchange box
    
    $dt = get-date #Gets Date & Time
    $authn = Get-ADUser $auth -Properties DisplayName | select -ExpandProperty DisplayName #Gets the administrators name
    $unn = Get-ADUser $un -Properties DisplayName | select -ExpandProperty DisplayName #Gets the disabled users name
    $mann = Get-ADUser $man -Properties DisplayName | select -ExpandProperty DisplayName #Gets the managers name
    
    $report = "Human Resources,
    
    The user account for $unn ($un) has been disabled from the company network as of $dt. All email messages will be forwarded to $mann ($man) for now on.
    
    Regards,
    
    $authn ($auth)"
    
    Send-MailMessage -To [email protected]<MyCompany>.com, [email protected]<MyCompany>.com -Subject "Disconnected User Report" -Body $report -From [email protected]<MyCompany>.com -SmtpServer <Exchange>
    

    A part of the NerdyDad's PowerShell Scripts Series



Looks like your connection to MangoLassi was lost, please wait while we try to reconnect.