Home > Blockchain >  E3 license clean up in Disabled user AD
E3 license clean up in Disabled user AD

Time:10-19

I need some help with a script :)

This script look in our AD for disabled accounts. Import to CSV then "compare through 0365 and check if the user have E3 license.

So what I would need help with is maybe if else or try catch statements. So if user are disabled in AD and have a E3 license export to CSV file.

When I ran script I get user not found red text is the maybe a way to handle all error text? Thanks in advance

$DisabledAccounts = Get-ADUser -Filter {Enabled -eq $false} | Select userprincipalname | Export-csv "C:\Temp\disabledADUser.csv"
$user = Import-Csv "C:\Temp\disabledADUser"
$user | ForEach-Object {
   $0365User= Get-MsolUser -UserPrincipalName $_.UserPrincipalName | Where-Object {($_.licenses).AccountSkuId -match "SPE_E3"} | Select userprincipalnameione -ErrorAction SilentlyContinue
if ($0365User) {

Write-Host " " -ForegroundColor "red"
}else {
Write-Host ""  -ForegroundColor "green"
}
}

CodePudding user response:

You should avoid filtering with curly brackets : -Filter { Enabled -eq $false }, but use instead double quotes -Filter "Enabled -eq $false"

However, since you only need UserPrincipalName attributes, I would prefer Search-ADAccount cmdlet.

Search-ADAccount -AccountDisabled -UsersOnly | ForEach-Object `
       -Begin { $o365Users = @() } `
       -Process { $o365Users  = Get-MsolUser -UserPrincipalName $_.UserPrincipalName | 
              Where-Object {($_.Licenses).AccountSkuId -match "SPE_E3"} | 
              Select UserPrincipalName -ErrorAction SilentlyContinue } `
       -End { $o365Users } | Export-CSV "C:\Temp\DisabledADUserWithLicenseAttached.csv"

the -Begin parameter for the ForEach-Object cmdlet is called at start only once to create an array which is populate in the -Process block, when all users have been verified, the -End block outputs the array to be converted into a csv.

For your information MSOnline PowerShell Module will be removed at the end of the year. You should consider using the Microsoft.Graph module instead (Here some informations about license management with it). You can also use PnP.PowerShell which is a very powerfull non-Microsoft and open source module but referenced by Microsoft here.

  • Related