Name, Department, #of Emails, Mailbox Size

Copper Contributor

Good afternoon!!

 

Would anyone have a PS.1 script that would provide a list of all users, their department name, the number of emails in the mailbox, and the size of their mailbox?

 

 

14 Replies
This should work
https://gallery.technet.microsoft.com/office/Generate-Mailbox-Size-and-3f408172

Simply running ".\Get-MailboxReport.ps1 -all" should create a csv file in the same directory.

@DeepakRandhawa Does this work for office 365/outlook mailboxes?

@lpmdvip I wrote this, I hope it covers your requirements. 
Just copy it to ISE Powershell and edit the folder/credentials/working paths and run it, the first time it will prompt you for your O365 creds, it will check the pssession status and open a new one(in case you have many MBXs). Let me know how it goes or if you have any questions. 

 <#
.SYNOPSIS
    Get MBXs Stats, User Attribute(s), Folder(s) Counts
.DESCRIPTION
    
.NOTES
    Author:     Erick A. Moreno
    Email:      emoreno@request-script.com
    Date:       12 Jan 2020
    PowerShell: v3
.References
#requested: https://techcommunity.microsoft.com/t5/windows-powershell/name-department-of-emails-mailbox-size/m-p/1167911
#>

$CredentialsFolder = "D:\Credentials\"
$WorkingDir        = "C:\Users\erick\Desktop\LogsFolder"
$ScriptTime        = Get-Date -UFormat "%m%d%Y-%H%M"

#region Functions
Function _Get-Sessions
 {
  Param(
        [Parameter(Mandatory=$true)]$CredentialsFolder,
        [Parameter(Mandatory=$true)]$CredentialsFileName
       )
  
  #region Check for Credentials File
  $TargetCredPath = $CredentialsFolder #Credential XML File Location
  $TargetCredName = $TargetCredPath + $CredentialsFileName
  #Write-Host $TargetCredName
  If(Test-Path $TargetCredName)
   {
    $TargetCred = Import-Clixml $TargetCredName
   }
  Else
   {
    $Cred = Get-Credential 
    $Cred | Export-CliXml -Path $(Join-Path -path $TargetCredPath -ChildPath RemotePS.cred)
    $TargetCred = Import-Clixml $TargetCredName
   }
  #endregion
  #region connections
  $Session  = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $TargetCred -Authentication Basic -AllowRedirection 
  $NoOutput = Import-PSSession $Session -AllowClobber -Prefix O365 -CommandName "*Mailbox*","*User*"
  #endregion
  Return  $Session
 }
#endregion
#region Open PS Sessions
$TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
#endregion

$MBXs = Get-O365Mailbox -ResultSize Unlimited 

$Counter = $MBXs.count
$Results = @()
$Counter

Foreach($MBX in $MBXs)
 {
  #Start-Sleep -Milliseconds 300
  $PsSessionState = $(Get-PsSession $TenantSession.Id).State  
  If($($Counter/100) -match '^[0-9]+$' -or $PsSessionState -ne "Opened")
   {
    Remove-PSSession $TenantSession.Id -Confirm:$false
    Write-Host "Opening a new Session Each 100 iterations" -ForegroundColor Yellow
    $TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
   }

  Write-Host "($Counter) Working On MBX: $($MBX.PrimarySmtpAddress)" -ForegroundColor Cyan
  $Stats       = $null
  $UserData    = $null
  $FolderItems = $null
  $UserData    = Get-O365User $MBX.PrimarySmtpAddress
  $Stats       = Get-O365MailboxStatistics -Identity $MBX.PrimarySmtpAddress
  $FolderItems = Get-O365MailboxFolderStatistics -Identity $MBX.PrimarySmtpAddress | Where {$_.Name -match “Inbox|Sent Items|Deleted Items|Junk E-Mail”} | Select Name,ItemsInFolder #Add Folders as needed
  
  $Properties  = [Ordered]@{
                            DisplayName        = $MBX.DisplayName
                            Department         = $UserData.Department #Add properties as needed
                            UserPrincipalName  = $MBX.UserPrincipalName
                            MailboxSizeMB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),4)
                            MailboxSizeGB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1GB),4)
                            InboxItems         = $($FolderItems | where{$_.Name -eq "Inbox"}).ItemsInFolder
                            SentItems          = $($FolderItems | where{$_.Name -eq "Sent Items"}).ItemsInFolder
                            DeletedItems       = $($FolderItems | where{$_.Name -eq "Deleted Items"}).ItemsInFolder
                            JunkItems          = $($FolderItems | where{$_.Name -eq "Junk E-Mail"}).ItemsInFolder
                            PrimarySMTPAddress = $MBX.PrimarySmtpAddress
                           }

  $Results += New-Object PSObject -Property $Properties
  
  $Counter--
 }

 $Results | Export-Csv -Path "$WorkingDir\ReportMBXsStats_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force

 Write-Host "Report Saved To: $WorkingDir\ReportMBXsStats_$ScriptTime.csv" -ForegroundColor Cyan




@Erick A. Moreno R. Thanks Erick! I'm running it now to see what it displays in the CSV. 

 

Would you be able to add a condition where the Department field is not blank?

 

@lpmdvip Sure, here you have.

 <#
.SYNOPSIS
    Get MBXs Stats, User Attribute(s), Folder(s) Counts
.DESCRIPTION
    
.NOTES
    Author:     Erick A. Moreno
    Email:      emoreno@request-script.com
    Date:       12 Jan 2020
    PowerShell: v3
.References
#requested: https://techcommunity.microsoft.com/t5/windows-powershell/name-department-of-emails-mailbox-size/m-p/1167911
#>

$CredentialsFolder = "D:\Credentials\"
$WorkingDir        = "C:\Users\erick\Desktop\LogsFolder"
$ScriptTime        = Get-Date -UFormat "%m%d%Y-%H%M"

#region Functions
Function _Get-Sessions
 {
  Param(
        [Parameter(Mandatory=$true)]$CredentialsFolder,
        [Parameter(Mandatory=$true)]$CredentialsFileName
       )
  
  #region Check for Credentials File
  $TargetCredPath = $CredentialsFolder #Credential XML File Location
  $TargetCredName = $TargetCredPath + $CredentialsFileName
  #Write-Host $TargetCredName
  If(Test-Path $TargetCredName)
   {
    $TargetCred = Import-Clixml $TargetCredName
   }
  Else
   {
    $Cred = Get-Credential 
    $Cred | Export-CliXml -Path $(Join-Path -path $TargetCredPath -ChildPath RemotePS.cred)
    $TargetCred = Import-Clixml $TargetCredName
   }
  #endregion
  #region connections
  $Session  = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $TargetCred -Authentication Basic -AllowRedirection 
  $NoOutput = Import-PSSession $Session -AllowClobber -Prefix O365 -CommandName "*Mailbox*","*User*"
  #endregion
  Return  $Session
 }
#endregion
#region Open PS Sessions
$TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
#endregion

$MBXs = Get-O365Mailbox -ResultSize Unlimited 

$Counter = $MBXs.count
$Results = @()
$NoDepartment = @()
$Counter

Foreach($MBX in $MBXs)
 {
  #Start-Sleep -Milliseconds 300
  $PsSessionState = $(Get-PsSession $TenantSession.Id).State  
  If($($Counter/100) -match '^[0-9]+$' -or $PsSessionState -ne "Opened")
   {
    Remove-PSSession $TenantSession.Id -Confirm:$false
    Write-Host "Opening a new Session Each 100 iterations" -ForegroundColor Yellow
    $TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
   }

  Write-Host "($Counter) Working On MBX: $($MBX.PrimarySmtpAddress)" -ForegroundColor Cyan
  $Stats       = $null
  $UserData    = $null
  $FolderItems = $null
  $UserData    = Get-O365User $MBX.PrimarySmtpAddress

  If(![string]::IsNullOrEmpty($($UserData.Department)))
   {
    $Stats       = Get-O365MailboxStatistics -Identity $MBX.PrimarySmtpAddress
    $FolderItems = Get-O365MailboxFolderStatistics -Identity $MBX.PrimarySmtpAddress | Where {$_.Name -match “Inbox|Sent Items|Deleted Items|Junk E-Mail”} | Select Name,ItemsInFolder #Add Folders as needed
    
    $Properties  = [Ordered]@{
                              DisplayName        = $MBX.DisplayName
                              Department         = $UserData.Department #Add properties as needed
                              UserPrincipalName  = $MBX.UserPrincipalName
                              MailboxSizeMB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),4)
                              MailboxSizeGB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1GB),4)
                              InboxItems         = $($FolderItems | where{$_.Name -eq "Inbox"}).ItemsInFolder
                              SentItems          = $($FolderItems | where{$_.Name -eq "Sent Items"}).ItemsInFolder
                              DeletedItems       = $($FolderItems | where{$_.Name -eq "Deleted Items"}).ItemsInFolder
                              JunkItems          = $($FolderItems | where{$_.Name -eq "Junk E-Mail"}).ItemsInFolder
                              PrimarySMTPAddress = $MBX.PrimarySmtpAddress
                             }
    
    $Results += New-Object PSObject -Property $Properties
   }
  Else
   {
    Write-Host "Department Field is Empty Skipping MBX: $($MBX.PrimarySmtpAddress)"
    $NoDepartment += $($MBX.PrimarySmtpAddress)
   }
  $Counter--
 }

 $Results | Export-Csv -Path "$WorkingDir\ReportMBXsStats_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 $NoDepartment | Export-Csv -Path "$WorkingDir\NoDepartmentField_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 Write-Host "Report Saved To: $WorkingDir\ReportMBXsStats_$ScriptTime.csv" -ForegroundColor Cyan
 Write-Host "Report Saved To: $WorkingDir\NoDepartmentField_$ScriptTime.csv" -ForegroundColor Cyan

@Erick A. Moreno R. Good afternoon! Should I be prompted to enter my credentials after every 100 iterations? Also, the csv "didnt have permission to write to a subfolder on my desktop". The script said it was there, but it was not. Any suggestions?

@lpmdvip Good afternoon. No, it should not prompt for creds, which means that the cred files is not been read correctly(Please verify that you have the cred file saved to the credentials folder). I've updated the script to use your documents folder as working dir and creds dir. Also, try to run the ISE as admin to avoid permissions issues to write/read the CSV files. Could you try to see what is saved to the variable $Results? If the data is already there, you don't have to run the whole script again just use the line 105 to export the report to a folder location that you have permissions to write on. 

 <#
.SYNOPSIS
    Get MBXs Stats, User Attribute(s), Folder(s) Counts
.DESCRIPTION
    
.NOTES
    Author:     Erick A. Moreno
    Email:      emoreno@request-script.com
    Date:       13 Jan 2020
    PowerShell: v3
.References
#requested: https://techcommunity.microsoft.com/t5/windows-powershell/name-department-of-emails-mailbox-size/m-p/1167911
#>

$CredentialsFolder = "$home\Documents\"
$WorkingDir        = "$home\Documents"
$ScriptTime        = Get-Date -UFormat "%m%d%Y-%H%M"

#region Functions
Function _Get-Sessions
 {
  Param(
        [Parameter(Mandatory=$true)]$CredentialsFolder,
        [Parameter(Mandatory=$true)]$CredentialsFileName
       )
  
  #region Check for Credentials File
  $TargetCredPath = $CredentialsFolder #Credential XML File Location
  $TargetCredName = $TargetCredPath + $CredentialsFileName
  #Write-Host $TargetCredName
  If(Test-Path $TargetCredName)
   {
    $TargetCred = Import-Clixml $TargetCredName
   }
  Else
   {
    $Cred = Get-Credential 
    $Cred | Export-CliXml -Path $(Join-Path -path $TargetCredPath -ChildPath RemotePS.cred)
    $TargetCred = Import-Clixml $TargetCredName
   }
  #endregion
  #region connections
  $Session  = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $TargetCred -Authentication Basic -AllowRedirection 
  $NoOutput = Import-PSSession $Session -AllowClobber -Prefix O365 -CommandName "*Mailbox*","*User*"
  #endregion
  Return  $Session
 }
#endregion
#region Open PS Sessions
$TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
#endregion

$MBXs = Get-O365Mailbox -ResultSize Unlimited 

$Counter = $MBXs.count
$Results = @()
$NoDepartment = @()
$Counter

Foreach($MBX in $MBXs)
 {
  #Start-Sleep -Milliseconds 300
  $PsSessionState = $(Get-PsSession $TenantSession.Id).State  
  If($($Counter/100) -match '^[0-9]+$' -or $PsSessionState -ne "Opened")
   {
    Remove-PSSession $TenantSession.Id -Confirm:$false
    Write-Host "Opening a new Session Each 100 iterations" -ForegroundColor Yellow
    $TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
   }

  Write-Host "($Counter) Working On MBX: $($MBX.PrimarySmtpAddress)" -ForegroundColor Cyan
  $Stats       = $null
  $UserData    = $null
  $FolderItems = $null
  $UserData    = Get-O365User $MBX.PrimarySmtpAddress

  If(![string]::IsNullOrEmpty($($UserData.Department)))
   {
    $Stats       = Get-O365MailboxStatistics -Identity $MBX.PrimarySmtpAddress
    $FolderItems = Get-O365MailboxFolderStatistics -Identity $MBX.PrimarySmtpAddress | Where {$_.Name -match “Inbox|Sent Items|Deleted Items|Junk E-Mail”} | Select Name,ItemsInFolder #Add Folders as needed
    
    $Properties  = [Ordered]@{
                              DisplayName        = $MBX.DisplayName
                              Department         = $UserData.Department #Add properties as needed
                              UserPrincipalName  = $MBX.UserPrincipalName
                              MailboxSizeMB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),4)
                              MailboxSizeGB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1GB),4)
                              InboxItems         = $($FolderItems | where{$_.Name -eq "Inbox"}).ItemsInFolder
                              SentItems          = $($FolderItems | where{$_.Name -eq "Sent Items"}).ItemsInFolder
                              DeletedItems       = $($FolderItems | where{$_.Name -eq "Deleted Items"}).ItemsInFolder
                              JunkItems          = $($FolderItems | where{$_.Name -eq "Junk E-Mail"}).ItemsInFolder
                              PrimarySMTPAddress = $MBX.PrimarySmtpAddress
                             }
    
    $Results += New-Object PSObject -Property $Properties
   }
  Else
   {
    Write-Host "Department Field is Empty Skipping MBX: $($MBX.PrimarySmtpAddress)"
    $NoDepartment += $($MBX.PrimarySmtpAddress)
   }
  $Counter--
 }

 $Results | Export-Csv -Path "$WorkingDir\ReportMBXsStats_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 $NoDepartment | Export-Csv -Path "$WorkingDir\NoDepartmentField_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 Write-Host "Report Saved To: $WorkingDir\ReportMBXsStats_$ScriptTime.csv" -ForegroundColor Cyan
 Write-Host "Report Saved To: $WorkingDir\NoDepartmentField_$ScriptTime.csv" -ForegroundColor Cyan

  

@Erick A. Moreno R. This worked perfectly!! Thank you!! One more thing - would you be able to add a column for the last time the mailbox was accessed?

@Erick A. Moreno R. I think the column name is lastuseractiontime.

@Erick A. Moreno R. More details - I need to know regarding the lastactionusertime column when was the last time they accessed their archived email.

@lpmdvip  Here you have. 

 <#
.SYNOPSIS
    Get MBXs Stats, User Attribute(s), Folder(s) Counts
.DESCRIPTION
    
.NOTES
    Author:     Erick A. Moreno
    Email:      emoreno@request-script.com
    Date:       12 Jan 2020
    PowerShell: v3
.References
#requested: https://techcommunity.microsoft.com/t5/windows-powershell/name-department-of-emails-mailbox-size/m-p/1167911
#>

$CredentialsFolder = "$home\Documents\"
$WorkingDir        = "$home\Documents"
$ScriptTime        = Get-Date -UFormat "%m%d%Y-%H%M"

#region Functions
Function _Get-Sessions
 {
  Param(
        [Parameter(Mandatory=$true)]$CredentialsFolder,
        [Parameter(Mandatory=$true)]$CredentialsFileName
       )
  
  #region Check for Credentials File
  $TargetCredPath = $CredentialsFolder #Credential XML File Location
  $TargetCredName = $TargetCredPath + $CredentialsFileName
  #Write-Host $TargetCredName
  If(Test-Path $TargetCredName)
   {
    $TargetCred = Import-Clixml $TargetCredName
   }
  Else
   {
    $Cred = Get-Credential 
    $Cred | Export-CliXml -Path $(Join-Path -path $TargetCredPath -ChildPath RemotePS.cred)
    $TargetCred = Import-Clixml $TargetCredName
   }
  #endregion
  #region connections
  $Session  = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $TargetCred -Authentication Basic -AllowRedirection 
  $NoOutput = Import-PSSession $Session -AllowClobber -Prefix O365 -CommandName "*Mailbox*","*User*"
  #endregion
  Return  $Session
 }
#endregion
#region Open PS Sessions
$TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
#endregion

$MBXs = Get-O365Mailbox -ResultSize Unlimited 

$Counter = $MBXs.count
$Results = @()
$NoDepartment = @()
$Counter

Foreach($MBX in $MBXs)
 {
  #Start-Sleep -Milliseconds 300
  $PsSessionState = $(Get-PsSession $TenantSession.Id).State  
  If($($Counter/100) -match '^[0-9]+$' -or $PsSessionState -ne "Opened")
   {
    Remove-PSSession $TenantSession.Id -Confirm:$false
    Write-Host "Opening a new Session Each 100 iterations" -ForegroundColor Yellow
    $TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
   }

  Write-Host "($Counter) Working On MBX: $($MBX.PrimarySmtpAddress)" -ForegroundColor Cyan
  $Stats       = $null
  $UserData    = $null
  $FolderItems = $null
  $UserData    = Get-O365User $MBX.PrimarySmtpAddress

  If(![string]::IsNullOrEmpty($($UserData.Department)))
   {
    $Stats       = Get-O365MailboxStatistics -Identity $MBX.PrimarySmtpAddress
    $FolderItems = Get-O365MailboxFolderStatistics -Identity $MBX.PrimarySmtpAddress | Where {$_.Name -match “Inbox|Sent Items|Deleted Items|Junk E-Mail”} | Select Name,ItemsInFolder #Add Folders as needed
    
    $Properties  = [Ordered]@{
                              DisplayName        = $MBX.DisplayName
                              Department         = $UserData.Department #Add properties as needed
                              UserPrincipalName  = $MBX.UserPrincipalName
                              MailboxSizeMB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),4)
                              MailboxSizeGB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1GB),4)
                              InboxItems         = $($FolderItems | where{$_.Name -eq "Inbox"}).ItemsInFolder
                              SentItems          = $($FolderItems | where{$_.Name -eq "Sent Items"}).ItemsInFolder
                              DeletedItems       = $($FolderItems | where{$_.Name -eq "Deleted Items"}).ItemsInFolder
                              JunkItems          = $($FolderItems | where{$_.Name -eq "Junk E-Mail"}).ItemsInFolder
                              LastLogon          = $Stats.LastLogonTime.ToString()
                              PrimarySMTPAddress = $MBX.PrimarySmtpAddress
                             }
    
    $Results += New-Object PSObject -Property $Properties
   }
  Else
   {
    Write-Host "Department Field is Empty Skipping MBX: $($MBX.PrimarySmtpAddress)"
    $NoDepartment += $($MBX.PrimarySmtpAddress)
   }
  $Counter--
 }

 $Results | Export-Csv -Path "$WorkingDir\ReportMBXsStats_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 $NoDepartment | Export-Csv -Path "$WorkingDir\NoDepartmentField_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 Write-Host "Report Saved To: $WorkingDir\ReportMBXsStats_$ScriptTime.csv" -ForegroundColor Cyan
 Write-Host "Report Saved To: $WorkingDir\NoDepartmentField_$ScriptTime.csv" -ForegroundColor Cyan




@lpmdvip 

Not sure that is possible, I think it is the same timestamp that you asked before: LastLogonTime. 

@Erick A. Moreno R. Just to confirm - My team originally found this Powershell:

 

Get-Mailbox "-resultsize unlimited" | Get-MailboxStatistics -archive | select displayname, lastuseractiontime > c:\reports\archiveslastaccessed.csv

 

Is there a way to incorporate this into your script? Or does the lastuseractiontime indeed simply confirm the last time they used any part of Outlook?

@lpmdvip Here you have. 
About the lastuseractiontime property, I haven't used that one before and not have documentation on its purpose. 

 <#
.SYNOPSIS
    Get MBXs Stats, User Attribute(s), Folder(s) Counts
.DESCRIPTION
    
.NOTES
    Author:     Erick A. Moreno
    Email:      emoreno@request-script.com
    Date:       12 Jan 2020
    PowerShell: v3
.References
#requested: https://techcommunity.microsoft.com/t5/windows-powershell/name-department-of-emails-mailbox-size/m-p/1167911
#>

$CredentialsFolder = "$home\Documents\"
$WorkingDir        = "$home\Documents"
$ScriptTime        = Get-Date -UFormat "%m%d%Y-%H%M"

#region Functions
Function _Get-Sessions
 {
  Param(
        [Parameter(Mandatory=$true)]$CredentialsFolder,
        [Parameter(Mandatory=$true)]$CredentialsFileName
       )
  
  #region Check for Credentials File
  $TargetCredPath = $CredentialsFolder #Credential XML File Location
  $TargetCredName = $TargetCredPath + $CredentialsFileName
  #Write-Host $TargetCredName
  If(Test-Path $TargetCredName)
   {
    $TargetCred = Import-Clixml $TargetCredName
   }
  Else
   {
    $Cred = Get-Credential 
    $Cred | Export-CliXml -Path $(Join-Path -path $TargetCredPath -ChildPath RemotePS.cred)
    $TargetCred = Import-Clixml $TargetCredName
   }
  #endregion
  #region connections
  $Session  = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $TargetCred -Authentication Basic -AllowRedirection 
  $NoOutput = Import-PSSession $Session -AllowClobber -Prefix O365 -CommandName "*Mailbox*","*User*"
  #endregion
  Return  $Session
 }
#endregion
#region Open PS Sessions
$TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
#endregion

$MBXs = Get-O365Mailbox -ResultSize Unlimited 

$Counter = $MBXs.count
$Results = @()
$NoDepartment = @()
$Counter

Foreach($MBX in $MBXs)
 {
  #Start-Sleep -Milliseconds 300
  $PsSessionState = $(Get-PsSession $TenantSession.Id).State  
  If($($Counter/100) -match '^[0-9]+$' -or $PsSessionState -ne "Opened")
   {
    Remove-PSSession $TenantSession.Id -Confirm:$false
    Write-Host "Opening a new Session Each 100 iterations" -ForegroundColor Yellow
    $TenantSession = _Get-Sessions -CredentialsFolder $CredentialsFolder -CredentialsFileName RemotePS.cred
   }

  Write-Host "($Counter) Working On MBX: $($MBX.PrimarySmtpAddress)" -ForegroundColor Cyan
  $Stats       = $null
  $UserData    = $null
  $FolderItems = $null
  $UserData    = Get-O365User $MBX.PrimarySmtpAddress

  If(![string]::IsNullOrEmpty($($UserData.Department)))
   {
    $Stats       = Get-O365MailboxStatistics -Identity $MBX.PrimarySmtpAddress -Archive 
    $FolderItems = Get-O365MailboxFolderStatistics -Identity $MBX.PrimarySmtpAddress | Where {$_.Name -match “Inbox|Sent Items|Deleted Items|Junk E-Mail”} | Select Name,ItemsInFolder #Add Folders as needed
    
    $Properties  = [Ordered]@{
                              DisplayName        = $MBX.DisplayName
                              Department         = $UserData.Department #Add properties as needed
                              UserPrincipalName  = $MBX.UserPrincipalName
                              MailboxSizeMB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),4)
                              MailboxSizeGB      = [math]::Round($($Stats.TotalItemSize.Value.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1GB),4)
                              InboxItems         = $($FolderItems | where{$_.Name -eq "Inbox"}).ItemsInFolder
                              SentItems          = $($FolderItems | where{$_.Name -eq "Sent Items"}).ItemsInFolder
                              DeletedItems       = $($FolderItems | where{$_.Name -eq "Deleted Items"}).ItemsInFolder
                              JunkItems          = $($FolderItems | where{$_.Name -eq "Junk E-Mail"}).ItemsInFolder
                              LastLogon          = $Stats.LastLogonTime.ToString()
                              lastuseractiontime = $Stats.lastuseractiontime 
                              PrimarySMTPAddress = $MBX.PrimarySmtpAddress
                             }
    
    $Results += New-Object PSObject -Property $Properties
   }
  Else
   {
    Write-Host "Department Field is Empty Skipping MBX: $($MBX.PrimarySmtpAddress)"
    $NoDepartment += $($MBX.PrimarySmtpAddress)
   }
  $Counter--
 }

 $Results | Export-Csv -Path "$WorkingDir\ReportMBXsStats_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 $NoDepartment | Export-Csv -Path "$WorkingDir\NoDepartmentField_$ScriptTime.csv" -NoTypeInformation -Encoding UTF8 -Force
 Write-Host "Report Saved To: $WorkingDir\ReportMBXsStats_$ScriptTime.csv" -ForegroundColor Cyan
 Write-Host "Report Saved To: $WorkingDir\NoDepartmentField_$ScriptTime.csv" -ForegroundColor Cyan