powershell script lastlogon office 365 and remove licenses

Nicola Venosta 1 Reputation point
2021-03-26T19:19:10.537+00:00

Hello, I am trying this script powershell to work; it remove Office 365 licenses from a csv file I added the rows marked in bold, which should check if the user have had not access in the last 30 days, but the script goes wrong The rows implicated in the error are the bold ones, because without them the script goes well ***

Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -Credential $credential
Connect-AzureAD -Credential $credential
$list = Import-CSV Utenti_da_Disabilitare.csv -delimiter ";"
forEach ($item in $list) {
$userUPN = $item.mail
$userList = Get-AzureADUser -ObjectID $userUPN
$LastLogonTime = Get-EXOMailboxStatistics -Identity $userUPN -Properties LastLogonTime
$OneMonthAgo = (Get-Date).adddays(-30)
if ($LastLogonTime -lt $OneMonthAgo)
{
$Skus = $userList | Select -ExpandProperty AssignedLicenses | Select SkuID
if($userList.Count -ne 0) {
if($Skus -is [array]) {
$licenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
for ($i=0; $i -lt $Skus.Count; $i++) {
$Licenses.RemoveLicenses += (Get-AzureADSubscribedSku | Where-Object -Property SkuID -Value $Skus[$i].SkuId -EQ).SkuID
}
Set-AzureADUserLicense -ObjectId $userUPN -AssignedLicenses $licenses
}
else{
$licenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$Licenses.RemoveLicenses = (Get-AzureADSubscribedSku | Where-Object -Property SkuID -Value $Skus.SkuId -EQ).SkuID
Set-AzureADUserLicense -ObjectId $userUPN -AssignedLicenses $licenses
}
}
}
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,390 questions
0 comments No comments
{count} votes