Advertisement
mariussm

Create-MailboxReport

Jun 6th, 2014
1,920
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .Synopsis
  3.    This script gets all users from AD based on a filter, checks the Exchange mailbox and outputs a
  4.    report containing useful information when determining wheter the mailbox is in use or not.
  5. .DESCRIPTION
  6.    This script gets all users from AD based on a filter, checks the Exchange mailbox and outputs a
  7.    report containing useful information when determining wheter the mailbox is in use or not.
  8.    
  9.    The output of the script contains the following information:
  10.    
  11.    DisplayName - The DisplayName of the mailbox
  12.    sAMAccountName = The account name of the mailbox
  13.    MailboxItemCount = The number of items in the mailbox
  14.    MailboxTotalItemSize = The total size of the mailbox
  15.    MailboxLastAccessedTime = Timestamp of the last time the mailbox was opened
  16.    LastLoggedOnUserAccount = The username of the user who last openend the mailbox
  17.    ADObjectWhenCreated = Timestamp of when the AD object was created
  18.    DistinguishedName = The DN of the AD object
  19.    HiddenFromAddressListsEnabled = True, false or unset - whether the object is hidden from the GAL
  20.    ForwardedTo = The account emails for this mailbox is automatically forwarded to
  21.    Manager = The DN of the manager
  22.    NumberOfAutomappings = The number of users that are automapping this mailbox
  23.    NumberOfDelegations = The number of users that have either full access or read permissions on the mailbox
  24.    ADObjectLastLogonTimeStamp = The last time the AD object of the mailbox logged on (useful if this is a service account only)
  25. .EXAMPLE
  26.    Create-MailboxReport -Verbose -Debug -CSV "MyReport.csv"
  27.    
  28.    Use default filter, but output to non-default csv location and use verbose and debug output
  29. .EXAMPLE
  30.     Create-MailboxReport -ADFilter {employeeid -notlike "*" -and mail -like "*"} -MaxResults 10
  31.    
  32.     Use a custom AD filter, and limit the result to 10 (useful for testing the report on only a few mailboxes)
  33. .EXAMPLE
  34.     Create-MailboxReport -ADFilter {targetaddress -like "*.onmicrosoft.com"} -ExchangeOnline:$true -ExchangeIdentifierAttribute userPrincipalName
  35.    
  36.     Use a custom AD filter, and connect to Exchange Online instead of on-premises
  37.    
  38.    
  39. #>
  40. function Create-MailboxReport {
  41.     [CmdletBinding()]
  42.     Param
  43.     (
  44.         [Parameter(Mandatory=$False,Position=0)]
  45.         [string]$CSV = "report.csv",
  46.  
  47.         [Parameter(Mandatory=$False,Position=1)]
  48.         [int]$MaxResults = 10000,
  49.    
  50.         [Parameter(Mandatory=$false)]
  51.         $ADFilter = {msExchRecipientTypeDetails -eq 2},
  52.    
  53.         [Parameter(Mandatory=$false)]
  54.         [bool] $ExchangeOnline = $false,
  55.  
  56.         [Parameter(Mandatory=$false)]
  57.         [ValidateSet("sAMAccountName", "userPrincipalName", "DistinguishedName", "mailNickname")]
  58.         $ExchangeIdentifierAttribute = "sAMAccountName"
  59.     )
  60.  
  61.     # Different approach between on-premises Exchange and Exchange Online
  62.     if($ExchangeOnline) {
  63.         # If Connect-ExchangeServer is available, we are in an Exchange PowerShell. That means we cannot load the Exchange Online cmdlets.
  64.         if(Get-Command "Connect-ExchangeServer" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue) {
  65.             Write-Error "Sorry, you are running an Exchange PowerShell and trying to connect to Exchange Online. Please open a regular PowerShell."
  66.             return;
  67.         }
  68.    
  69.         # If Get-Mailbox already exists, there is not reason to connect again.
  70.         if(!(Get-Command "Get-Mailbox" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue)) {
  71.             Write-Verbose "Connecting to Exchange Online"
  72.             $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Authentication Basic -AllowRedirection -Credential (Get-Credential)
  73.             Import-PSSession $session -DisableNameChecking
  74.         } else {
  75.             Write-Verbose "Already connected to Exchange Online?"
  76.         }
  77.     } else {
  78.         # Load RemoteExchange if Connect-ExchangeServer is not present
  79.         if(!(Get-Command "Connect-ExchangeServer" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue)) {
  80.             Write-Verbose "Loading RemoteExchange"
  81.             $remoteExchange = 'C:\Program Files\Microsoft\Exchange Server\V14\Bin\RemoteExchange.ps1'
  82.             if(Test-Path $remoteExchange) {
  83.                 . $remoteExchange
  84.             } else {
  85.                 Write-Error "Could not find $remoteExchange"
  86.                 return;
  87.             }
  88.         }
  89.  
  90.         Write-Verbose "Connecting to Exchange on-premises"
  91.         Connect-ExchangeServer -Auto
  92.     }
  93.  
  94.     Write-Verbose "Loading AD module"
  95.     Import-Module ActiveDirectory -Verbose:$false
  96.  
  97.     Write-Verbose ("Getting max {0} users from AD matching filter: {1}" -f $MaxResults, $ADFilter)
  98.     Write-Progress -Activity "Getting user objects from AD" -Status " " -PercentComplete 20
  99.     $adusers = Get-ADUser -filter $ADFilter -Properties lastlogontimestamp,whencreated,DisplayName,altRecipient,msExchHideFromAddressLists,Manager,msExchDelegateListLink,mailNickname -ResultSetSize $MaxResults
  100.     Write-Progress -Activity "Getting user objects from AD" -Status " " -PercentComplete 100 -Completed
  101.  
  102.     $inc = 1;
  103.     $adusers | foreach{
  104.         $AD = $_ # This makes it a bit more easy to read
  105.         Write-Progress -Activity "Running" -Status ("{0}/{1} - {2}" -f $inc, $adusers.Count, $AD.SamAccountName) -PercentComplete ($inc / $adusers.Count * 100) ; $inc++    
  106.         Write-Debug "Getting mailbox statitics"
  107.    
  108.         # Get mailbox statistics for mailbox. If it fails, give warning but continue with the rest of the mailboxes.
  109.         $MAILBOXSTATISTICS = Get-MailboxStatistics -Identity $AD.$ExchangeIdentifierAttribute -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
  110.         if(!$MAILBOXSTATISTICS) {
  111.             Write-Warning ("Could not find mailbox statics for {0}" -f $AD.$ExchangeIdentifierAttribute )
  112.             return;
  113.         }
  114.    
  115.         # Get all mailboxe permissions that are not inherited, that is not on the form "NT AUTHORITY\SELF" and the SID is resolvable
  116.         Write-Debug "Getting mailbox permissions"
  117.         $MAILBOXPERMISSION = Get-MailboxPermission -Identity $AD.$ExchangeIdentifierAttribute | where{!$_.IsInherited} | where{([string]$_.User) -notlike "NT AUTH*"} | where{([string]$_.User) -notlike "S-1-5-21-*"}
  118.         Write-Debug ("Found {0} mailbox permissions" -f ($MAILBOXPERMISSION | measure).Count)
  119.    
  120.         # Extract a few attributes
  121.         $lastlogontimestamp = if($AD.lastlogontimestamp){$AD.lastlogontimestamp}else{0}
  122.    
  123.    
  124.         # Create hashmap with all properties
  125.         $properties = @{
  126.             DisplayName = $AD.DisplayName
  127.             sAMAccountName = $AD.SamAccountName
  128.             MailboxItemCount = $MAILBOXSTATISTICS.ItemCount
  129.             MailboxTotalItemSize = $MAILBOXSTATISTICS.TotalItemSize
  130.             MailboxLastAccessedTime = $MAILBOXSTATISTICS.LastLogonTime
  131.             ADObjectWhenCreated = $AD.whencreated
  132.             DistinguishedName = $AD.DistinguishedName
  133.             HiddenFromAddressListsEnabled = $AD.msExchHideFromAddressLists
  134.             ForwardedTo = $AD.altRecipient
  135.             LastLoggedOnUserAccount = $MAILBOXSTATISTICS.LastLoggedOnUserAccount
  136.             Manager = $AD.Manager
  137.             NumberOfAutomappings = ($AD.msExchDelegateListLink | measure).Count
  138.             NumberOfDelegations = ($MAILBOXPERMISSION | measure).Count
  139.             ADObjectLastLogonTimeStamp = [datetime]::FromFileTime($lastlogontimestamp)
  140.         }
  141.    
  142.         # Create custom object
  143.         return New-Object -TypeName PSObject -Property $properties
  144.     } | Export-Csv -Path $CSV -Encoding UTF8 -NoTypeInformation -Delimiter ";"
  145.  
  146.     Write-Progress -Activity "Running" -Status "Completed" -PercentComplete 100 -Completed
  147.     Write-Output "$CSV created"
  148. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement