I needed to grab all the mobile devices that had emails attached to them not too long ago. I could have gone through the GUI, and spent a few days trying my best to document everything, or I could use Powershell to pull the O365 Mobile Devices. Can you guess which one I did? Yep, PowerShell is a way of thinking nowadays in the system admin world.
The Script
Connect-ExchangeOnline
$Mailboxes = get-mailbox -all
$Devices = foreach ($Mail in $Mailboxes) {
$MobileDevices = Get-MobileDevice -Mailbox $mail.userprincipalname
foreach ($Device in $MobileDevices) {
$Stats = Get-MobileDeviceStatistics -Identity $Device.Identity
[pscustomobject]@{
User = $mail.userprincipalname
FriendlyName = $Device.FriendlyName
name = $Device.name
Identity = $Device.Identity
DeviceID = $Device.DeviceId
DeviceOS = $Device.DeviceOS
DeviceType = $Device.DeviceType
DeviceModel = $Device.DeviceModel
ClientType = $Stats.ClientType
FirstSyncTime = $Device.FirstSyncTime
WhenChanged = $Device.WhenChanged
LastPolicyUpdateTime = $Stats.LastPolicyUpdateTime
LastSyncAttemptTime = $Stats.LastSyncAttemptTime
LastSuccessSync = $stats.LastSuccessSync
DeviceAccessState = $Device.DeviceAccessState
DeviceAccessStateReason = $Device.DeviceAccessStateReason
IsValid = $Device.IsValid
Status = $Stats.Status
DevicePolicyApplied = $stats.DevicePolicyApplied
DevicePolicyApplicationStatus = $stats.DevicePolicyApplicationStatus
}
}
}
$Devices
The Break Down
This script is pretty straightforward. We first connect to exchange online. Currently, this script is designed to work with MFA. Then we grab all the mailboxes from O365.
Connect-ExchangeOnline
$Mailboxes = get-mailbox -all
Next, we loop through these mailboxes. We drop all the information get gather from this loop into a variable. I called my devices. Once again, nothing great or grand.
$Devices = foreach ($Mail in $Mailboxes) {}
For each mailbox we have, we pull all of the devices from that mailbox. Since a single mailbox can have more than one device, we loop through these devices. For each loop, we want to grab that device’s stats to gain more insights.
$MobileDevices = Get-MobileDevice -Mailbox $mail.userprincipalname
foreach ($Device in $MobileDevices) {
$Stats = Get-MobileDeviceStatistics -Identity $Device.Identity
Finally, from there we gather the information into a single object. These commands produce a lot of information. It’s best to parse it down some. That’s what I did with the next part. That’s how I am able to get all the O365 Mobile Devices using PowerShell.