rss logo

Delete Office 365 users with PowerShell

Here how to delete Exchange Online Users with PowerShell script.


Import-Module MSOnline
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -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