简体   繁体   中英

PowerShell to Get Disabled AD Users Still Licensed in O365

I'm trying to run a report, to get all the users who are disabled in AD, but still have a license assigned in Office 365. I've found a couple of scripts on various sites, and they work if just run within the PowerShell console, but the moment I try to export to a CSV, it loses the license assignment information.

The script I'm currently using is:

Get-MsolUser -All | where {$_.isLicensed -eq $true -and $_.BlockCredential -eq $true} | select userprincipalname,islicensed,Licenses,UsageLocation

This works, and shows the below

UserPrincipalName IsLicensed Licenses UsageLocation

----------------- ---------- -------- -------------

joe.bloggs@domain.com True {tennent:ENTERPRISEPACK} US

However, the moment I add:

| Export-Csv -Path C:\LicenseReport.csv

The report changes to:

UserPrincipalName IsLicensed Licenses UsageLocation

joe.bloggs@domain.com TRUE System.Collections.Generic.List`1[Microsoft.Online.Administration.UserLicense] US

I've tried a number of other select properties for the license, such as

  • $_.licenses.accountskuid
  • @{n="Licenses
  • Type";e={$_.Licenses.AccountSKUid}} $($license.AccountSKUid)

But none work. How do I get the report to export with the License details?

Try this:

Get-MsolUser -All | where {$_.isLicensed -eq $true -and $_.BlockCredential -eq $true} | 
select userprincipalname,islicensed,@{N="Licenses";E={$_.Licenses.AccountSkuId}},UsageLocation

and that's in case you have only one license, but if you have more, you need to join them with commas so it will be a string compatible for the csv export, for example:

Change this:

@{N="Licenses";E={$_.Licenses.AccountSkuId}}

To This:

@{N="Licenses";E={$_.Licenses.AccountSkuId -join ','}}

This is the command I use & it works:

Get-MsolUser -All | ?{$_.isLicensed-eq "TRUE"} | Select DisplayName, SignInName, @{n="LicensesType";e={$_.Licenses.AccountSKUid}} | Export-Csv -Path C:\output.csv -NoTypeInformation

Be aware though, the MSOnline module is no longer developed. You should consider moving to the AzureAD PowerShell module . Here is the syntax for that:

Get-AzureADUser -All 1 | ?{($_.AssignedLicenses | ?{$_.SkuId -eq $license.SkuId})} | SELECT DisplayName, UserPrincipalName, @{l="License";e={$license.SkuPartNumber}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM