PowerShell Script To Remove Office 365 Users From CSV Input

Overview

In this blog, we will learn how to write a PowerShell script which will read principal user name from the CSV file and remove those users from Office 365 account.

Step 1

Connect Windows Azure Active Directory Module for Windows PowerShell.

Use the following code snippet to connect with Office 365 tenant.

  1. $UserCredential = Get-Credential      
  2. Connect-AzureAD -Credential $UserCredential    

Step 2

Execute the following script.

Below is a screenshot for my CSV file.

Windows PowerShell
  1. $sInputFile = "D:\deleteuser.csv"  
  2. $sColumnName = "UserPrincipalName"  
  3. $tblDatos = Import - CSV $sInputFile  
  4. foreach($fila in $tblDatos)   
  5. {  
  6.     "Deleting user " + $fila.$sColumnName.ToString()  
  7.     Write - Host - ForegroundColor Yellow "User staring to deleter"  
  8.     $fila.$sColumnName  
  9.     Remove - MsolUser - UserPrincipalName $fila.$sColumnName  
  10.     Write - Host - ForegroundColor Yellow $fila.$sColumnName "Deleted........"  
  11.     $fila.  
  12.     $sColumnName  
  13. }  
It will ask for confirmation for deleting every user.

Windows PowerShell

Press "Yes".

Conclusion

This is how we can use PowerShell script to delete multiple users from Office 365.

Ebook Download
View all
Learn
View all