O365 license removal script

hitender singh 126 Reputation points
2021-08-09T06:45:41.583+00:00

Hello,

I am trying to run the below script but it fails with the error mentioned below.

Start-Transcript -Path "C:\Script\trans.txt"

[array]$wpausers = @(Import-Csv -Path "C:\Script\userswpa.csv")

foreach ($wapuser in $wpausers) {
    try {
        $msuser = Get-MsolUser -UserPrincipalName $wpauser.email -ErrorAction stop
    }
    catch {
        Write-Host "User lookup failed for $($wpauser.email)"
    }   
    if ($msuser) {
        try {
            Set-MsolUserLicense -UserPrincipalName $msuser.Userprincipalname -RemoveLicenses “tenant2:DYN365_ENTERPRISE_P1_IW” -ErrorAction stop
            write-host "successfully removed the license for user" $msuser.Userprincipalname
        }
        catch {
            Write-Host "Failed to remove license for $($msuser.Userprincipalname)"
        }   
    }
}

stop-transcript

Would appreciate any help

$error shows
Set-MsolUserLicense : Cannot bind argument to parameter 'UserPrincipalName' because it is null.
At line:3 char:48

  • Set-MsolUserLicense -UserPrincipalName $wpauser.email -Remove ...
  • ~~~~~~~~~~~~~~
  • CategoryInfo : InvalidData: (:) [Set-MsolUserLicense], ParameterBindingValidationException
  • FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Online.Administration.Automatio
    n.SetUserLicense

This works:-

[array]$rusers = @(Import-Csv -Path "C:\Script\userswpa.csv")

foreach ($user in $rusers) {
Set-MsolUserLicense -UserPrincipalName $user.email -RemoveLicenses “tenant2:DYN365_ENTERPRISE_P1_IW”
}

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,381 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,568 questions
0 comments No comments
{count} votes

Accepted answer
  1. Vasil Michev 95,666 Reputation points MVP
    2021-08-09T07:22:53.773+00:00

    Your catch statement needs to terminate processing, or skip to the next user. Add a 'continue' as follows:

         try {
             $msuser = Get-MsolUser -UserPrincipalName $wpauser.email -ErrorAction stop
         }
         catch {
             Write-Host "User lookup failed for $($wpauser.email)"
             continue
         }   
    

0 additional answers

Sort by: Most helpful