Disable a User w/ O365

Going along with the current theme, we need to be able to disable a user. This script is setup for administrators that is interfaced with O365 & Exchange Online. Does the same thing as the other Disable a User script, but forwards the emails on Exchange Online instead of Exchange On Premises.

[cc lang=”PowerShell”]
#(Module 2.02)
Import-Module activedirectory
Import-Module MSOnline

$un = Read-Host “Who are we disabling today? (Login Credentials)” #(Module 2.03)
$man = Read-Host “Who are we forwarding mail to? (Login Credentials)” #(Module 2.04)
$auth = Read-Host “Who are you? (Login Credentials)” #(Module 2.05)

#Resets the old user’s password (Module 2.06)
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 https://outlook.office365.com/powershell-liveid/ -Authentication Basic -Credential $cred -AllowRedirection #(Module 2.07-Part 1)
Import-PSSession $mail -WarningAction SilentlyContinue | Out-Null #(Module 2.07-Part 2)
Set-Mailbox $un -ForwardingAddress $man -RemovePicture #Sets the forwarding address to the manager and removes their picture (Module 2.08)
Remove-PSSession -Session $mail #Disconnects from the Exchange box (Module 2.09)

#Removes License in O365
Connect-MsolService #(Module 2.10)
Set-MsolUserLicense -UserPrincipalName (-join($un,’@.com’)) -RemoveLicenses #(Module 2.11)

$dt = get-date #Gets Date & Time (Module 2.12)
$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.


$authn ($auth)” #(Module 2.13)

Send-MailMessage -To [email protected].com, [email protected].com -Subject “Disconnected User Report” -Body $report -From [email protected].com -SmtpServer #(Module 2.14)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.