rss logo

Delete Office 365 users with PowerShell

Here how to delete Exchange Online Users with PowerShell script.

Prerequisites

Instructions

users1@domain.net
users2@domain.net
users3@domain.net
[...]
usersN@domain.net
Import-Module MSOnline
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
Connect-MsolService -Credential $UserCredential

# Put the users into an array
$array = Get-Content C:\Users\std\Desktop\userlist.txt

foreach($item in $array){
             Write-Host "$item" #show current user
             Get-Mailbox -Identity "$item" #test if the user exist
             #Remove-MsolUser -UserPrincipalName "$item"
             #remove-mailuser -identity "$item"

	     # remove the account (mailboxe + account)
             Remove-MsolUser -UserPrincipalName "$item" -Force 
	     # log if it is OK or not
             if ($? -eq '$True') { 
                "$item : OK" | Out-File "C:\Users\std\Desktop\result.txt" -Append
             } else {
                "$item : KO" | Out-File "C:\Users\std\Desktop\result.txt" -Append
             }
             #Remove-Mailbox -Identity "$item" -Permanent $true
}
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Contact :

contact mail address