Management

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 772 other subscribers

Social

  • LinkedIn
  • RSS Feed for Posts
  • Twitter
  • StumbleUpon

O365 : Mailbox report for Office 365 in HTML

This week I’ve created a HTML report where Office 365 mailboxes are sorted in order of size.

The standard tools of Office 365 don’t give the satisfaction, of the info I needed.

( See : https://www.vspbreda.nl/nl/2014/11/o365-mail-protection-reports-for-office-365/ )

Therefore I created a HTML script for showing the Office 365 mailbox, sorted in size.

The script can be used with the -verbose option.

Also check the log file in the report folder, for more debugging options

 

First download or copy the powershell script.

[wpdm_file id=2 title=”true” ]

<#
.Synopsis
    Generates HTML Report in MB.
	  
.Description
	This scripts generates a HTML report, sorted in size of the mailbox.
	The script is stored at the location $ReportPath
	The variable $SendEmail
		$True => The Info will been send by E-mail to $MailTo
		$False => No Info will been send by E-mail

.Inputs
	No Inputs are necessary

.Outputs
	The HTML files are the outputs
			
.Notes
    Name: MailboxReportInMB-O365-v10.ps1
    Author: Richard Voogt
    Version: 1.0
    Date: October 8 2014
    Tested on Windows 8, Windows 8.1
	Written By: Richard Voogt
	Website:	http://www.vspbreda.nl
	Twitter:	http://twitter.com/rvoogt

.Change-Log
	V1.0 	10/08/2014 	- Initial version

.Link
	https://www.vspbreda.nl/nl/2014/11/o365-mailbox-report-for-office-365-in-html/
   
.EXAMPLE
	For normal execution:
	.\MailboxReportInMB-O365-v10.ps1
	
	For testing purposes :
	.\MailboxReportInMB-O365-v10.ps1 -verbose    
#>

[CmdletBinding()]
param ()
 
#Don't edit between the lines
# ------------------------
$Date = ( get-date ).ToString('yyyy/MM/dd')
$ReportDate=get-date -uformat "%Y-%m-%d-%H%M"
# ------------------------

#importing variables
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
# For testing purposes
write-Verbose "Files are taken from the folder $Mydir"
# Import settings from the config file
$ConfigFile = Get-Content "$MyDir\MailboxReportInMB-O365-v10.xml"

$MailFrom=$ConfigFile.Settings.MailFrom
$MailTo=$ConfigFile.Settings.MailTo
$MailServer=$ConfigFile.Settings.MailServer
$SendMail=$ConfigFile.Settings.SendMail
$ReportPath=$ConfigFile.Settings.ReportPath
$Customer=$ConfigFile.Settings.Customer
$LogDays=$ConfigFile.Settings.LogDays
$EmailSubject="Mailbox report in MB"
$SaveOutputFile = "Mailbox-Report-in-MB-$($ReportDate)-$Customer.html"
$SendAttachmentName = "$Reportpath\$SaveOutputFile"
$Bodytext = "See the attachment"
$Today=get-date -f dd-MM-yyyy-hh-mm
$Subject = "$Customer - $Today - $EmailSubject"
$backuplog="$Reportpath\Log\"+"$Today"+"-backup-$Customer.log"
# $AttachmentArray = @()
$Header = @"
            <html>
            <head>
            <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
            <title>DiskSpace Report</title>
            <STYLE TYPE="text/css">
			TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
			TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
			TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
			.odd  { background-color:#ffffff; }
			.even { background-color:#dddddd; }
			</style>
			<title> $EmailSubject </title>
			</style>
            </head>
            <body>
            <table width='100%'>
            <tr bgcolor='#CCCCCC'>
            <td colspan='7' height='25' align='center'>
            <font face='tahoma' color='#003399' size='4'><strong>$Customer Mailbox report in MB - $date</strong></font>
            </td>
            </tr>
            </table>
"@

# For debugging purposes
write-Verbose "MailFrom = $MailFrom"
write-Verbose "MailTo = $MailTo"
write-Verbose "MailServer = $MailServer"
write-Verbose "SendMail = $SendMail"
write-Verbose "ReportPath = $ReportPath"
write-Verbose "Customer = $Customer"
write-Verbose "LogDays = $LogDays"
write-Verbose "Subject = $Subject"
write-Verbose "SaveOutputFile = $SaveOutputFile"
write-Verbose "SendAttachmentName = $SendAttachmentName"
write-Verbose "backuplog = $backuplog"


# Connect to Office 365
Function ConnectOnline{
Write-Output ("----------- Connecting to Office 365 on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
$LiveCred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session -AllowClobber
} 	# End Function ConnectOnline

# Create report directory and Output file
Function CreateReportPath
{
    if(!(Test-Path -Path $Reportpath\ )){
        New-Item -ItemType directory -Path $Reportpath\
		Write-Output ("----------- Reportpath $Reportpath created on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Verbose ("Log created in location $Reportpath\")
    }
}	 # End Function CreateReportPath
	
# Creating log file
Function CreateLog
{
    if(!(Test-Path -Path $Reportpath\Log\ )){
        New-Item -ItemType directory -Path $Reportpath\Log\
		Write-Output ("----------- Log path $Reportpath\Log\ created on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Output ("----------- Log file $SaveOutputFile created on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Output ("----------- Logging Startted on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Verbose ("Log created in location $Reportpath\Log\")
	}
} 	# End Function CreateLog

# Creating Output File
Function CreateOutputfile
{
    New-Item -path $Reportpath -name $SaveOutputFile -itemtype "file" 
	Write-Output ("----------- Output File $SaveOutputFile created on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
} 	# End Function CreateOutputfile

# Clean out logging after number of $logDays
Function CleanLogs
{
    Write-Output ("----------- Cleaning backups logs older than $LogDays days - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
    $limit = (Get-Date).AddDays(-$LogDays)
    Get-ChildItem -Path $Reportpath\log -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
	Write-Verbose ("Logs cleaned to $LogDays days")
} 	# End Function CleanLogs
	
# Check if -SendMail parameter set and if so check -SendBody and -SendAttachment are set
Function CheckEmailSettings
{
Write-Output ("----------- Function CheckEmailSettings started  on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
# Check if -SendMail parameter set and if so check -MailFrom, -MailTo and -MailServer are set
If ($SendMail)
	{	  
	If (!$MailFrom -or !$MailTo -or !$MailServer -or !$Subject)
		{
		cls
        Write-Host -backgroundcolor Red -ForegroundColor White '*************************************************************************************'
		Write-Host -backgroundcolor Red -ForegroundColor White '*                                                                                   *'
		Write-Host -backgroundcolor Red -ForegroundColor White '* If -SendMail specified, you must also specify -MailFrom, -MailTo and -MailServer  *'
		Write-Host -backgroundcolor Red -ForegroundColor White '*                                                                                   *'
		Write-Host -backgroundcolor Red -ForegroundColor White '*************************************************************************************'
		Write-Host ''
		Write-Output ("----------- Checking Sending Variables on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Output ("Missing one of these variables") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Output ("MailFrom = $MailFrom") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Output ("MailTo = $MailTo") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Write-Output ("MailServer = $MailServer") | Out-File "$backuplog" -Encoding ASCII -Force -Append
        BREAK
        } # End If
	} #End IF $SendMailEmail
} 	# End Function CheckEmailSettings
	
# 3. Function Alternating Lines.
Function Set-AlternatingLines 
{
    [CmdletBinding()]
   	Param(
       	[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
        [string]$Line,
   	    [Parameter(Mandatory=$True)]
       	[string]$EvenLine,
        [Parameter(Mandatory=$True)]
   	    [string]$OddLine
		)
	Begin
		{
		$ClassName = $EvenLine
		}
	Process 
		{
		If ($Line.Contains("<tr>"))
			{	$Line = $Line.Replace("<tr>","<tr class=""$ClassName"">")
				If ($ClassName -eq $EvenLine)
					{	
					$ClassName = $OddLine
					}
				Else
					{	
					$ClassName = $EvenLine
					}
			}
		Return $Line
		} # End Process AlternatingLines
} # End Function Set-AlternatingLines

Function MailboxReportInMB 
	{
	[CmdletBinding()]
	param(
    )
 
	BEGIN
	{
		Write-Output ("----------- Function MailboxReportInMB started on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append      
		# Start Function writeHtmlHeader
		Function writeHtmlHeader
			{
			param($fileName)
			} # End Function WriteHtmlHeader
	} # End Begin
 
	Process	{
		writeHtmlHeader "$SendAttachmentName"      
			# First write down the start so there is something on the screen
            Write-Host 'Starting collecting data for : '  $Customer 

			$UserMailboxStats = Get-Mailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited | Get-MailboxStatistics
			$UserMailboxStats | Add-Member -MemberType ScriptProperty -Name TotalItemSizeInBytes -Value {$this.TotalItemSize -replace "(.*\()|,| [a-z]*\)", ""}
			$UserMailboxStats | Select-Object DisplayName, TotalItemSizeInBytes, @{name="TotalItemSize (MB)"; expression={[math]::Round( ($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),3)}}, ItemCount | Sort "TotalItemSize (MB)" -Descending | ConvertTo-HTML -Head $Header | Set-AlternatingLines -EvenLine even -OddLine odd | Out-File  $SendAttachmentName
			Write-Output ("----------- Stats created on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append

			# First write down the a message for the user so there is something on the screen
            Write-Host -backgroundcolor Green -ForegroundColor Black 'Exchange Online Passed for '  $Customer 			
		} # End Process
 
	END {
            Write-Host '' 
			Write-Host -backgroundcolor Green -ForegroundColor Black 'Files saved at : ' $SendAttachmentName 
            Write-Host '' 
			Write-Output ("----------- Files saved at : $SendAttachmentName on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		} # End End
	} # End Function MailboxReportInMB
 
Function StartScript
{
		Write-Output ("----------- Function StartScript on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
		Send-Mailmessage -from $MailFrom -to $MailTo -subject $Subject -smtpserver $MailServer -body $bodytext -Attachments $SendAttachmentName -bodyasHTML -verbose 
} 	# End Function StartScript
 
Function CloseLogging
{
Write-Output ("----------- Closing log on - $(Get-Date -DisplayHint DateTime)") | Out-File "$backuplog" -Encoding ASCII -Force -Append
} 
 
 
# Start the script
CreateReportPath
CreateLog
CreateOutputfile
CleanLogs
ConnectOnline
CheckEmailSettings
MailboxReportInMB
StartScript
CloseLogging    

 

Second add the desired settings in the MailboxReportInMB-O365-v10.xml file.

XML file :

<?xml version="1.0"?>
<Settings>
      <MailFrom>rvoogt@vspbreda.nl</MailFrom>
      <MailTo>rvoogt@vspbreda.nl</MailTo>
      <MailServer>smtp.ISP.nl</MailServer>
	  <!--  Value $False is No e-mail will be send, value $true is send e-mail -->
      <SendMail>$True</SendMail> 		
      <ReportPath>C:\Scripts\MailboxrightsInMB\reports</ReportPath>
      <Customer>VSPBreda</Customer>
	  <LogDays>30</LogDays>
</Settings>

 

Third start the Azure Active Directory-module for Windows PowerShell as an administrator

And start the ps1 script.

Enter the Office 365 credentials

And the report is created in HTML format, and send to the e-mail address placed in the XML file.