PowerShell to Get Disabled AD Users Still Licensed in O365 - powershell

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?

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}}

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 ','}}

Related

PowerShell - Find Oldest Email

I am stuck, I am trying to find the oldest "EMAIL" in a person's mailbox, but I don't know what else to try. I think I need to add the ContainerClass -eq "IPF.Note" somewhere, but I am not sure where.
The following script works, but it finds the oldest ITEM, which in my case it is a contact. I want to look at each container (Email, Chats, Calendar, Contacts) separately, but for this script, I just want to know the oldest email.
Thank you
Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity USERID |
Where OldestItemReceivedDate -ne $null |
Sort OldestItemReceivedDate |
Select -First 1 OldestItemReceivedDate
You can filter what you have by item type, but I would do it after getting the statistics so you only have to query exchange once:
# Get the folder statistics for all folders
$stats = Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity $USERID
# Get the oldest email. Can re-use $stats for the other item types
$OldestEmail = $stats |
Where-Object {$_.OldestItemReceivedDate -and $_.ContainerClass -eq 'IPF.Note'} |
Sort-Object OldestItemReceivedDate |
Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1
# Outputs
ContainerClass OldestItemReceivedDate FolderPath
-------------- ---------------------- ----------
IPF.Note 2/8/2016 2:07:50 PM /Inbox
You are correct that the mailbox folder statistics command does not search recoverable items by default. It also does not search the mailbox archive unless you specify -Archive. If you need these, you'll have to do additional searches:
# Get recoverable items:
Get-MailboxFolderStatistics -Identity $USERID -FolderScope 'RecoverableItems' -IncludeOldestAndNewestItems |
Where-Object OldestItemReceivedDate |
Sort-Object OldestItemReceivedDate |
Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1
# Note that deleted item containers do not have an item type!
ContainerClass OldestItemReceivedDate FolderPath
-------------- ---------------------- ----------
2/5/2016 3:41:33 PM /Deletions
Presuming this is for compliance reasons to search a mailbox for items on an Exchange Server you should be using the Search-Mailbox cmdlet - https://learn.microsoft.com/en-us/powershell/module/exchange/search-mailbox?view=exchange-ps
For Exchange Online to search a mailbox for items you should use the New-ComplianceSearch cmdlet https://learn.microsoft.com/en-us/powershell/module/exchange/new-compliancesearch?view=exchange-ps
This web page shows how to search by date - New-ComplianceSearch: how to use the newer version of Search-Mailbox https://www.codetwo.com/admins-blog/new-compliancesearch-new-version-of-search-mailbox/
This web page has a script to search mailboxes, including dates PowerShell – New-ComplianceSearch script to go through all mailboxes, find a target message, and remove it - https://365basics.com/powershell-new-compliancesearch-script-to-go-through-all-mailboxes-find-a-target-message-and-remove-it/
Using your original approach, should be done like this. Presuming you have appropriate permissions.
Get-MailboxFolderStatistics -ID <mailboxemailaddress> -IncludeOldestAndNewestItems | select Identity, Name, FolderPath, ItemsInFolder, FolderSize, OldestItemReceivedDate | Export-Csv C:\temp\Mailbox.csv -NoTypeInformation

How to obtain user principal names from canonical name of objects

When I run below PowerShell command:
(Get-Mailbox -Identity SharedMailbox1).GrantSendOnBehalfTo
I get the following output:
contoso.local/NZ/Users/Internal/Test, User21
contoso.local/NZ/Users/Terminated/Test, User12
contoso.local/NZ/Users/Terminated/Test, User3
contoso.local/NZ/Users/Internal/Test, User6
contoso.local/NZ/Users/Internal/Test, User10
I would like to obtain UPN from this output in an array. Is there a way?
This is actually straightforward. The GrantSendOnBehalfTo property contains objects of type [Microsoft.Exchange.Data.Directory.ADObjectId] which are suitable to be piped other cmdlets in the Exchange Management Shell.
(Get-Mailbox SharedMailbox1).GrantSendOnBehalfTo |
Get-Mailbox |
Select-Object -ExpandProperty UserPrincipalName
A shorter but less readable version:
((Get-Mailbox SharedMailbox1).GrantSendOnBehalfTo | Get-Mailbox).UserPrincipalName
You can also use it in conjunction with the ActiveDirectory module. You just have to insure you're piping a string down the pipeline that the AD cmdlets will accept for their -Identity parameter. Of course, you can't go wrong using the DistinguishedName:
((Get-Mailbox SharedMailbox1).GrantSendOnBehalfTo.DistinguishedName |
Get-ADObject -Properties UserPrincipalName).UserPrincipalName
I should point out that while rare it's possible to have a group in the GrantSendOnBehalfTo property. Groups do not have a UserPrincipalName attribute. you can get around that using Get-Recipient and filtering on Recipient Type:
(Get-Mailbox SharedMailbox1).GrantSendOnBehalfTo |
Get-Recipient |
Where-Object{$_.RecipientType -eq "UserMailbox"} |
Get-Mailbox |
Select-Object -ExpandProperty UserPrincipalName
Or the AD version:
(Get-Mailbox SharedMailbox1).GrantSendOnBehalfTo.DistinguishedName |
Get-ADObject -Properties UserPrincipalName |
Where-Object{$_.objectClass -eq "user"} |
Select-Object -ExpandProperty UserPrincipalName
There may be other object types too, but so long as you're filtering for user mailboxes you should be able to output correct data. Of course, these techniques can be expanded to report better if non-user/mailboxes are encountered etc...

Powershell script not getting all information needed from Office 365 (MsolService)

I am trying to get certain information from our Office 365 but not getting all the information required.
Below is my script I use:
Get-MsolUser -All | select DisplayName, LastPasswordChangeTimeStamp, LastLogonTime, PrimaryEmailAddress | Export-CSV UserList.csv -NoTypeInformation
The information I am getting from the above script is only the display name last password change. For the LastLogonTime and PrimaryEmailAddress I get nothing.
Is there something I am doing wrong?
Please help.
Thanks
Last logon time can be retrieved from Get-MailboxStatistics but it shows last accessed Exchange mailbox alone. It doesn't track other Office 365 services. You can try below code for your requirement.
$Result=""
$Output=#()
Get-mailbox -All | foreach{
$UPN=$_.UserPrincipalName
$DisplayName=$_.DisplayName
$PrimaryEmailAddress=$_.ProxyAddresses.where{$_ -clike "SMTP:*"} -creplace "SMTP:"
$LastPwdChange=$_.LastPasswordChangeTimeStamp
$LastLogonTime=(Get-MailboxStatistics -Identity $upn).lastlogontime
$Result= #{'DisplayNme'=$DisplayName;'LastLogonTime'=$LastLogonTime;'PrimaryEmailAddress'=$PrimaryEmailAddress;'LastPwdChange'=$LastPwdChange}
$Output= New-Object PSObject -Property $Result
$Output | Select-Object DisplayName,LastLogonTime,PrimaryEmailAddress,LastPwdChange | Export-CSV UserList.csv -Notype -Append
}

Export all users NOT in AAD security group with PowerShell?

I need to export all users who are not a member of a certain security group to a CSV file, using PowerShell.
Pretty straight forward, I know, but I can only find methods of exporting users who do meet certain criteria, not methods of exporting users who don't. I found one method that works but only with Active Directory.
I'm currently using this to pull all users:
Get-MSOLUser -all | Where-Object { $_.isLicensed -eq "True"} | Select-Object UserPrincipalName | Export-Csv C:\365\users.csv
And am aiming to get something like this:
Get-MSOLUser -all | Where-Object { $_.isLicensed -eq "True", isNotMemberofGroup ""} | Select-Object UserPrincipalName | Export-Csv C:\365\users.csv
I am unsure how to add an additional condition that only pulls members that are not in a certain security group, using the following logic - dump upn to csv if user is licensed, and if user is not member of group xxx.

Trying to use Get-MsolUser to get a list of Microsoft only users in AD but it returns everything

I'm using the Get-MsolUser to get a list of all the users in the active directory. However, I just want the user where the Source is "Microsoft" instead of "Windows Server AD". This command does not return the Source nor does it give me the option to filter on the source. This is what I am doing:
Connect-MsolService
Connect-AzureAD
Get-MsolUser | Where-Object {$_.isLicensed -eq 'True'} | Format-List | Out-File "C:\Azure Scripts\userlist.txt"
Has anybody ever used this or any other command to get a list of only the Microsoft accounts?
You may use the following cmdlet:
Get-MsolUser -All | select userprincipalname,islicensed, {$.Licenses.AccountSkuId} |Where-Object {$.isLicensed -eq 'True'}| Format-List | Out-File "C:\Users\azure\Desktop\Get-Msoluserlist.txt"
Refer : Get-MsolUser