public/Get-O365Reports.ps1
<#
.Synopsis This PowerShell cmdlet allows you to generate many different reports about your Office 365 Mailboxes. .Description AVAILABLE REPORTS ------------------ The Get-O365Reports cmdlet allows you to generate reports about your organizations Office 365 Mailboxes. More specifically, you can generate reports for: "MailboxSize" = total size of the each mailbox in your organization in GB sorted in descending order "ArchiveSize" = allocated archive sizes for mailboxes "MailboxHold" = mailbox hold status for each mailbox in your organization "LastLogin" = users last login "ActiveSync" = ActiveSync for connected devices per account "MailboxInfo" = general information about each mailbox "Forwarding" = mailbox Forwarding info "DBGroups" = lists all distribution groups for your organization "DBMembers" = lists all members of a specific distribution group for your organization "UserLicense" = user license reports FORMATTING REPORTS ------------------- You have the option to generate the report in CSV, HTML, or a Live Viewing format. Both the CSV and HTML generated reports will save a file to your computer. You can specify where to save the report and if the folder does not exist, it will be created. If you opt to not specify a save location, by default, reports will save to your home drive ($env:HOMEDRIVE) in a folder named "Reports". Subfolders are created for each report and file type. The syntax of the command to generate reports only requires you to pass 2 variables: '-ReportName' and '-Formatting'. The report name parameter specifies which report you want to run. The formatting specifies the format of the report you wish to generate.Setting '-Formatting' to: "CSV" will create a comma spaced variable report which you can open and use with Excel or any spreadsheet software. "HTML" report will create a report that can be viewed with your web browser. You have the option to set the color of the output for this report (Blue, Green, or Red) by specifying the $ReportColor variable. By default, HTML reports will be in blue. LiveView will DESCRIPTION OF PARAMATERS ------------------------- Required parameters include: -ReportName = mandatory parameter that specifies which report you want to generate -Formatting = mandatory parameter that specifies the formatting of the report you are generating. Options include: CSV, HTML, and LiveView. NOTE: does not save any information and only gives you a temporary 'Live View' of the report you wish to generate. Optional parameters include: -Savepath = used to specify where to save your report. By default this is your home drive in the folder named 'Reports' (i.e. - C:\Reports). Subfolders for report names and file types are created. -DBAlias = used for generating the Distribution Group Member report. If you forget to include this parameter, you will get a prompt to input it before the report gets generated. -OpenReport = used to open the report upon completion of generating it automatically -ReportColor = sets the color scheme for HTML reports generated FOLDER STRUCTURE FOR SAVING REPORTS ----------------------------------- When reports are generated, the folder structure is as follows: [Root Folder]\[ReportName Folder]\csv\[ReportName_DateString].csv (i.e. - C:\Reports\MailboxSize\csv\MailboxSize_2018-04-23T15-01-58.csv) OR [Root Folder]\[ReportName Folder]\html\[ReportName_DateString].csv (i.e. - C:\Reports\MailboxSize\html\MailboxSize_2018-04-23T15-01-58.html) Filenames for reports have a prefix of the numeric date and time along with the type of report you are generating. All reports generated are exported in CSV format and are easily opened using any spreadsheet software or text editor. .Example Get-O365Reports -ReportName MailboxSize -Formatting csv Description ----------- This is the simplest way to run this command with the least amount of parameters. This will create a CSV file of a report generated to display all mailbox sizes in your organization in descending order. The file that is created will be located in your C:\Reports folder because a save path was not specified. Subfolders will be created so that the CSV file is located in C:\Reports\MailboxSize\csv\MailboxSize__2018-04-23T15-01-58.CSV. Replace the report name of 'Mailboxsize' to any other report name to quickly create CSV reports. Available report names are: Mailboxsize ; ArchiveSize ; MailboxHold ; LastLogin ; ActiveSync ; MailboxInfo ; Forwarding ; DBGroups ; DBMembers ; UserLicense NOTE: The DBMembers report will require you pass the '-DBAlias' Parameter. If you don't, you will get a prompt to do so. .Example Get-O365Reports -ReportName MailboxSize -Formatting html Description ----------- This is the same report as Example 1, but it will create an HTML file for your report. By default, the color scheme is blue. The file that is created will be located in your C:\Reports folder because a save path was not specified. Subfolders will be created so that the HTML file is located in C:\Reports\MailboxSize\csv\MailboxSize__2018-04-23T15-01-58.HTML. Replace the report name of 'Mailboxsize' to any other report name to quickly create CSV reports. Available report names are: Mailboxsize ; ArchiveSize ; MailboxHold ; LastLogin ; ActiveSync ; MailboxInfo ; Forwarding ; DBGroups ; DBMembers ; UserLicense NOTE: The DBMembers report will require you pass the '-DBAlias' Parameter. If you don't, you will get a prompt to do so. .Example Get-O365Reports -ReportName MailboxSize -Formatting html -Savepath $env:USERPROFILE\documents -OpenReport yes -ReportColor red Description ----------- This runs the same reports as Example 1, although now a custom save path has been specified, along with a different report formatting. The report generated will be saved to the Documents folder and use the red color theme (Color options = Blue, Green, Red). Also it will auto open once complete as the user set the '-OpenReport' parameter to yes. .Example Get-O365Reports -ReportName DBMembers -Formatting html -DBAlias "All Personnel" Description ----------- This report uses the '-DBAlias' parameter which is only needed with the DBMembers report. The result of issuing the above command is a report with all members of the Distribution Group by the name of "All Personnel" in your organization assuming "AllPersonnel" is a valid Distribution Group. #> Function Get-O365Reports{ [cmdletbinding()] Param ( [Parameter(Position=0,mandatory=$true)] [string]$ReportName, [Parameter(Position=1,mandatory=$true)] [string]$Formatting, [Parameter(Position=2,mandatory=$false)] [string]$SavePath, [Parameter(Position=3,mandatory=$false)] [string]$DBAlias, [Parameter(Position=4,mandatory=$false)] [string]$OpenReport, [Parameter(Position=5,mandatory=$false)] [string]$ReportColor ) # End of Parameters Process { Test-O365Connection $datestring = (Get-Date).ToString("s").Replace(":","-") IF ($Formatting -eq "csv" -OR $Formatting -eq "html") { # If the optional parameter $SavePath has no value, all generated reports are saved in the 'Home Drive' of the system. # The default folder will be set to 'Reports'(typically, this will be 'C:\Reports'), and a subfolder will be created if # it doesn't already exist to organize file types for reports. IF ($SavePath -eq "") { $SavePath = "$env:HOMEDRIVE"+"\Reports\"+"$ReportName"+"_Reports\"+"$Formatting" $filename = "$SavePath"+"\"+"$ReportName"+"_$datestring"+'.'+"$Formatting" } Else { IF ($ReportName -ne "DBMembers") { $SavePath = "$SavePath"+"\"+"$ReportName"+"_Reports\"+"$Formatting" $filename = "$SavePath"+"\"+"$ReportName"+"_$datestring"+'.'+"$Formatting" } Else { $SavePath = "$SavePath"+"\"+"$ReportName"+"_Reports\"+"$Formatting" $filename = "$SavePath"+"\"+"$ReportName"+"_$DBAlias"+"_$datestring"+'.'+"$Formatting"} } # The folder will be created corresponding to the $SavePath parameter if it does not already exist IF (-NOT (Test-Path $SavePath -PathType 'Container')) { New-Item $SavePath -ItemType Directory -Force } } switch ($ReportName) { MailboxSize { $data = Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select DisplayName,@{name="TotalItemSize (GB)";expression={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1024MB),2)}},@{name="TotalDeletedItemSize (GB)";expression={[math]::Round(($_.TotalDeletedItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1024MB),2)}},ItemCount,DeletedItemCount | Sort "TotalItemSize (GB)" -Descending } ArchiveSize { $data = Get-Mailbox -Archive -ResultSize Unlimited | Get-MailboxStatistics -Archive | Select DisplayName,StorageLimitStatus,@{name="TotalItemSize (MB)";expression={[math]::Round((($_.TotalItemSize.Value.ToString()).Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}},@{name="TotalDeletedItemSize (MB)";expression={[math]::Round((($_.TotalDeletedItemSize.Value.ToString()).Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}},ItemCount,DeletedItemCount | Sort "TotalItemSize (MB)" -Descending } MailboxHold { $data = Get-Mailbox | Select DisplayName,InPlaceHolds } LastLogin { $data = Get-Mailbox | Foreach {Get-MailboxStatistics $_.Identity | Select DisplayName, LastLogonTime, LastLogoffTime} } ActiveSync { $data = get-MobileDevice | Select ID, FriendlyName, DeviceIMEI, DeviceMobileOperator, DeviceOS, DeviceTelephoneNumber, DeviceType, DeviceModel | Sort ID } MailboxInfo { $data = get-mailbox | Select ID, PrimarySmtpAddress, WhenCreated, WhenChanged, ProhibitSendReceiveQuota, RecoverableItemsQuota, ProtocolSettings, RecipientLimits, MailboxPlan, WhenMailboxCreated, IsDirSynced | Sort ID } Forwarding { $data = Get-Mailbox | Where {$_.ForwardingsmtpAddress -ne $null} | Select Name, ForwardingsmtpAddress, DeliverToMailboxAndForward } DBGroups { $data = Get-DistributionGroup | Select DisplayName, PrimarySmtpAddress, LitigationHoldDuration, RetentionPolicy } DBMembers { if ($dbalias -eq $null) {Write-Host "Error: Missing paramater '-DBAlias' in command. Please re-enter command with the -DBAlias parameter." -ForegroundColor Red} else { $check = ((Get-DistributionGroup $dbalias -ErrorAction 'SilentlyContinue').IsValid) -eq $true if ($check -eq "True") {$data = Get-DistributionGroupMember -identity $DBAlias | Select Identity, PrimarySMTPAddress, RecipientType | Sort Identity} else { Write-Host "Error: The '-DBAlias' parameter does not represent a valid Distribution Group Alias Name for your organization. Please retry with a valid Distribution Group Alias." -ForegroundColor Red } } } UserLicense { $data = Get-MsolUser -All | Sort-Object -Property @{Expression={$_.isLicensed}; ascending=$true}, @{Expression={$_.SignInName}; ascending=$true}| Select SignInName,isLicensed,UsageLocation,UserType,ValidationStatus,WhenCreated } default { Write-host "Invalid Report Name" -ForegroundColor Red $generatFile = "False" } } # The below 'if' statement prevents a file from being generated when an invalid report is set for the 'ReportName' parameter If ($generatFile -ne "False") { switch ($formatting) { CSV { $data | Export-CSV -Path $filename -NoTypeInformation # If parameter $OpenReport is set to 'Yes' the report will automatically open upon completion. IF ($OpenReport -eq 'y' -OR $OpenReport -eq 'yes') { write-host "$ReportName report complete! Opening report to review: $filename" -ForegroundColor Green Invoke-Item $filename } Else { write-host "$ReportName report complete! File saved to: $filename" -ForegroundColor Green } } HTML { $modpath = (Get-Module -ListAvailable O365Tools).path.ToString() $CSSLoc = $modpath -replace ("O365tools.psd1","style\") switch ($ReportColor) { Green {$stylesheet = "$CSSLoc"+"greenTable.css"} Blue {$stylesheet = "$CSSLoc"+"blueTable.css"} Red {$stylesheet = "$CSSLoc"+"redTable.css"} default {$stylesheet = "$CSSLoc"+"bluetable.css"} } $css = get-content $stylesheet $data | ConvertTo-Html -Head $css -Body "<h1>$ReportName Report</h1>`n<h5>Generated on $(Get-Date)</h5>" | Out-File -FilePath $filename # If parameter $OpenReport is set to 'Yes' the report will automatically open upon completion. IF ($OpenReport -eq 'y' -OR $OpenReport -eq 'yes') { write-host "$ReportName report complete! Opening report to review: $filename" -ForegroundColor Green Invoke-Item $filename } Else { write-host "$ReportName report complete! File saved to: $filename" -ForegroundColor Green } } LiveView { $data | Out-GridView -Title "$ReportName Report - Live View" -Wait } } } } #End Process } |