############################################################################################################################################
# Script that allows to do a massive unlicensing of Office 365 users. The users are read from a CSV file.
# The csv file only needs one column that stores the account principal name to be unlicensed in each iteration.
# The column's title in this case needs to be UserPrincipalName
# Required Parameters:
# ->$sInputFile: Name or path of the file with the users to be deleted.
# ->$sColumName: Name of the reference column to be used when reading the file
############################################################################################################################################
#This is a thread option to improve memory utilization in powershell scripts
$host.Runspace.ThreadOptions = "ReuseThread"
#This establishes Connection to Office 365
$usercredential = get-credential -credential "ENTERCREDENTIALSHERE"
Connect-MsolService -Credential $usercredential
#Definition of the function that allows to unlicense the Office 365 users contained in the CSV file.
$myAccountSKUID = "ENTERSKUIDHERE"
function Unlicense-Office365Users
{
param ($sInputFile,$sColumnName)
try
{
# Reading the CSV file
$bFileExists = (Test-Path $sInputFile -PathType Leaf)
if ($bFileExists) {
"Loading $InvFile for processing..."
$tblDatos = Import-CSV $sInputFile
} else {
Write-Host "$sInputFile file not found. Stopping the import process!" -ForegroundColor Red
exit
}
# Ulicensing the users
Write-Host "Unlicensing the Office 365 users ..." -foregroundcolor Green
foreach ($fila in $tblDatos)
{
"Unlicensing user " + $fila.$sColumnName.ToString()
$licenseduser = $fila.$sColumnName
Get-MsolUser -UserPrincipalName $licenseduser | Set-MsolUserLicense -RemoveLicenses $myAccountSKUID
}
Write-Host "-----------------------------------------------------------" -foregroundcolor Blue
Write-Host "All the users have been unlicensed. The processs is completed." -foregroundcolor Blue
Write-Host "-----------------------------------------------------------" -foregroundcolor Blue
}
catch [System.Exception]
{
Write-Host -ForegroundColor Red $_.Exception.ToString()
}
}
#$ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
$ScriptDir = $PSScriptRoot
$sInputFile=$ScriptDir+ "ENTERCSVPATHHERE"
$sColumnName="UserPrincipalName"
Unlicense-Office365Users -sInputFile $sInputFile -sColumnName $sColumnName