param( [switch]$includeMailboxFolderPermissions ) ### Do not change the variable below as it is needed to prevent truncation of data in the output $FormatEnumerationLimit=-1 # Exchange Auth start ### load ex shell $snapin = Get-PSSnapin -Registered Microsoft.Exchange.Management.PowerShell.E* -ErrorAction 'SilentlyContinue' if ($snapin -eq $null){Write-Warning "Snapin not available"} else { $command = Get-Command "Get-Mailbox" -ErrorAction SilentlyContinue if ($command -eq $null) { Write-Host "Loading Exchange Commands" Add-PSSnapin $snapin -ErrorAction 'SilentlyContinue' } else {Write-Host "Exchange Snapin is already loaded"} } # Exchange Auth end $OrgSettings = Get-OrganizationConfig $Kunde = $OrgSettings.Name ### Update the log path variable below before running the script #### $logpath = "$PSScriptRoot\EXOnprem-Doku" if(-not (Test-Path $logpath)){md $logpath} cd $logpath #region BasicStuff Get-AcceptedDomain | Select Name,DomainName,DomainType,Default | export-csv ($logpath+"\"+$kunde+"_AcceptedDomains.csv") -notypeinformation -delimiter ";" -encoding utf8 Get-ReceiveConnector | select Name, @{Name="Max Message Size (MB)";expression={"$([math]::round($_.MaxMessageSize.Tobytes() /1Mb, 2))"}}, @{N="Server";E={[string]$a = $_.fqdn;$b=$a.Split(".");$b[0]}}, @{N="Bindings";E={[string]$_.Bindings}}, @{N="Receive mail from";E={[string]$_.RemoteIPRanges}}, @{N="Authentication";E={[string]$_.AuthMechanism}}, @{N="Permission Groups";E={[string]$_.PermissionGroups}} | sort Server | Export-Csv ($logpath+"\"+$kunde+"_ReceiveConnectors.csv") -Delimiter ";" -notypeinformation Get-SendConnector | select Name, @{N="AdressSpaces";E={[string]$_.AddressSpaces}}, @{N="Smart Hosts";E={[string]$_.SmartHosts}}, @{N="SourceTransportServers";E={[string]$_.SourceTransportServers}},Enabled | Export-Csv ($logpath+"\"+$kunde+"_SendConnectors.csv") -notypeinformation -delimiter ";" -encoding utf8 Get-TransportRule | Select Name,Priority,Description,Comments,State | export-csv ($logpath+"\"+$kunde+"_TransportRules.csv") -notypeinformation -delimiter ";" -encoding utf8 Get-OwaMailboxPolicy | Select Name,ActiveSyncIntegrationEnabled,AllAddressListsEnabled,CalendarEnabled,ContactsEnabled,JournalEnabled,JunkEmailEnabled,RemindersAndNotificationsEnabled,NotesEnabled,PremiumClientEnabled,SearchFoldersEnabled,SignaturesEnabled,SpellCheckerEnabled,TasksEnabled,ThemeSelectionEnabled,UMIntegrationEnabled,ChangePasswordEnabled,RulesEnabled,PublicFoldersEnabled,SMimeEnabled,RecoverDeletedItemsEnabled,InstantMessagingEnabled,TextMessagingEnabled,DirectFileAccessOnPublicComputersEnabled,WebReadyDocumentViewingOnPublicComputersEnabled,DirectFileAccessOnPrivateComputersEnabled,WebReadyDocumentViewingOnPrivateComputersEnabled | export-csv ($logpath+"\"+$kunde+"_OwaMailboxPolicies.csv") -notypeinformation -delimiter ";" -encoding utf8 Get-MobileDeviceMailboxPolicy | Select Name,AllowNonProvisionableDevices,DevicePolicyRefreshInterval,PasswordEnabled,MaxCalendarAgeFilter,MaxEmailAgeFilter,MaxAttachmentSize,RequireManualSyncWhenRoaming,AllowHTMLEmail,AttachmentsEnabled,AllowStorageCard,AllowCameraTrue,AllowWiFi,AllowIrDA,AllowInternetSharing,AllowRemoteDesktop,AllowDesktopSync,AllowBluetooth,AllowBrowser,AllowConsumerEmail,AllowUnsignedApplications,AllowUnsignedInstallationPackages | export-csv ($logpath+"\"+$kunde+"_MobileDevicePolices.csv") -notypeinformation -delimiter ";" -encoding utf8 Get-OrganizationRelationship | Select Name,DomainNames,FreeBusyEnabled,FreeBusyAccessLevel,FreeBusyAccessScope | export-csv -NoTypeInformation ($logpath+"\"+$kunde+"_Free-Busy-OrgRels.csv") #endregion #region MailboxData # MailboxData laden, aufbereiten und exportieren Write-host "## Getting basic mailbox and permissions data ###" -ForegroundColor Cyan $start=get-date write-host "Starting: $start" #mailboxes laden Write-host "Getting mailbox data of ALL users..." -NoNewline $now=get-date $users = get-mailbox -resultsize unlimited Write-host "This took $(((get-date)-$now).minutes) minutes and $(((get-date)-$now).seconds) seconds." #mailboxes exportieren Write-host "Exporting mailbox data..." -NoNewline $now=get-date $users | select UserPrincipalName,Identity,prim*,alias,account*,recipienttype*,IsInactiveMailbox,Office,ExchangeUserAccountControl | export-csv ($logpath+"\"+$kunde+"_Mailboxes.csv") -NoTypeInformation -Delimiter ";" -Encoding UTF8 Write-host "This took $(((get-date)-$now).minutes) minutes and $(((get-date)-$now).seconds) seconds." $outfile=$kunde+"_MBXCount.csv" $users | group recipienttypedetails | select Count,Name | export-csv $outfile -Delimiter ";" -NoTypeInformation -Encoding UTF8 $groupmbx=Get-Mailbox -GroupMailbox -ResultSize unlimited $groupmbx | group recipienttypedetails | select Count,Name | export-csv $outfile -Delimiter ";" -NoTypeInformation -Encoding UTF8 -Append $pfmbx = get-mailbox -PublicFolder -ResultSize unlimited $pfmbx | group recipienttypedetails | select Count,Name | export-csv $outfile -Delimiter ";" -NoTypeInformation -Encoding UTF8 -Append $arcmbx = get-mailbox -Archive -ResultSize unlimited $arcmbx | group recipienttypedetails | select Count,@{Name="Name";Expression={"MBX with Archive"}} | export-csv $outfile -Delimiter ";" -NoTypeInformation -Encoding UTF8 -Append #endregion #region MailboxPermissionData Write-host "Exporting mailbox permission data..." -NoNewline $now=get-date ########################## changed vom einzeiler in das hier so dass auch hier der UPN als Anker mit in die perms.csv fließt und verwendet werden kann, da die identity auch schon mal eine guid sein kann $itemtotalcount=$users.Count $itemcount=1 [array]$csvdata=@() foreach($user in $users){ #Progressbar $progress = $itemcount / $itemtotalcount *100 ; Write-Progress -Activity "Get-MailboxPermission" -PercentComplete $progress -Status "$itemcount/$itemtotalcount - Processing [$($user.Alias)]" $itemcount++ $perms=Get-MailboxPermission $user | ?{$_.User -notmatch "SELF" -and $_.IsInherited -eq $false} | select Identity,User,@{N="AccessRights";E={[string]$_.AccessRights}} $perms | Add-Member -MemberType NoteProperty -Name 'UserPrincipalName' -Value $user.UserPrincipalName $csvdata += $perms } $csvdata | select UserPrincipalName,Identity,User,AccessRights | export-csv ($logpath+"\"+$kunde+"_MailboxPermissions.csv") -NoTypeInformation -Delimiter ";" -Encoding UTF8 # FORWARDING $users | select Alias,ForwardingAddress | ?{$_.ForwardingAddress -ne $null} | export-csv ($logpath+"\"+$kunde+"_MailboxesForwardTo.csv") -NoTypeInformation -Delimiter ";" -Encoding UTF8 # SENDAS $users | %{Get-RecipientPermission $_.Name -AccessRights SendAs | ?{$_.Trustee -notmatch "SELF"}} | select Identity,Trustee | export-csv ($logpath+"\"+$kunde+"_MailboxesSendAs.csv") -NoTypeInformation -Delimiter ";" -Encoding UTF8 # SENDONBEHALF $users | select Alias,@{n="GrantSendOnBehalfTo";e={$_.GrantSendOnBehalfTo -join "§"} }| ?{$_.GrantSendOnBehalfTo} | export-csv ($logpath+"\"+$kunde+"_MailboxesSendOnBehalf.csv") -NoTypeInformation -Delimiter ";" -Encoding UTF8 Write-host "This took $(((get-date)-$start).minutes) minutes and $(((get-date)-$start).seconds) seconds." Write-Host "Finished." -ForegroundColor Green Write-Host "`n" #region MailboxFolderPermissions # FOLDERPERMS function get-MailboxFolderPermissionsForAllFolders{ param( [string]$mailbox ) $user=get-mailbox $mailbox $mbx = $user $smtp=$mbx.PrimarySMTPaddress #Write-host "Processing [$smtp]" $activity = "Get-MailboxFolderPermissions - Folder" $stats=Get-MailboxFolderStatistics $mbx $permstoexport=@() #Progressbar $itemtotalcount = $stats.count $itemcount = 1 foreach($folder in $stats){ $progress = $itemcount / $itemtotalcount *100 ; $fldname=$folder.Name.replace("","/") #replace spec char used by EXO to represent a "/" with a real "/" - if any Write-Progress -Activity $activity -PercentComplete $progress -Status "$itemcount/$itemtotalcount - Processing [$fldname]" -ParentId 1 #Write-host "`t Checking [$fldname]" $skip="Recoverable Items", "SubstrateHolds", "Purges", "Deletions", "Calendar Logging", "Versions" $special="Top of Information Store","Oberste Ebene des Informationsspeichers", "Haut de la banque d'informations", "Bovenste map van gegevensarchief" $folderWithColon=$null $1stPart=$folder.Identity.ToString().split("\")[0] $2ndPart=[string]$folder.Identity.ToString().split("\")[1] if($2ndPart -in $skip){Write-Verbose "`t`t Skipping [$2ndPart]";break} $folderWithColon=($folder.identity.ToString()).replace($1stPart,$1stPart + ":"); if($2ndPart -in $special){$folderWithColon=$folderWithColon.ToString().Replace($2ndPart,"")} $folderWithColon = [string]$folderWithColon.ToString().replace("","/") $perm=$null $perm=get-MailboxFolderPermission $folderWithColon; $permtoexport = $perm | select identity,FolderName,User,@{Name="AccessRights";Expression={$_.AccessRights}},SharingPermissionFlags $permtoexport = $permtoexport | ?{$_.User -notlike "Default*" -and $_.User -notlike "Standard*" -and $_.User -notlike "Anonym*"} $permstoexport += $permtoexport #$out = $perm | ConvertTo-Json -Depth 1 if($permtoexport){ $out = $permtoexport | select FolderName,User,AccessRights,SharingPermissionFlags Write-Verbose "Found ($out | ConvertTo-Json)" } $itemcount=$itemcount+1 } Write-Progress -Activity $activity -Completed -ParentId 1 return $permstoexport } if($includeMailboxFolderPermissions){ Write-host "## Getting mailbox FOLDER permission data ##" -ForegroundColor Cyan $start=get-date write-host "Starting: $start" if(-not (Test-Path $logpath\MBXPerms)){md $logpath\MBXPerms} $mbxtotalcount = $users.count $mbxcount = 1 # Fortschrittsanzeige $activity = "Get-MailboxFolderPermissions - Mailbox" $progress = ($mbxcount / $mbxtotalcount) * 100 Write-Progress -Activity $activity -PercentComplete $progress -Status "$mbxcount/$mbxtotalcount - Processing [$($mbx.Alias)]" -Id 1 foreach ($mbx in $users) { # Debugging-Ausgabe Write-Verbose "Processing mailbox: $($mbx.Alias) - $mbxcount/$mbxtotalcount" # Fortschrittsanzeige $progress = ($mbxcount / $mbxtotalcount) * 100 Write-Progress -Activity $activity -PercentComplete $progress -Status "$mbxcount/$mbxtotalcount - Processing [$($mbx.Alias)]" -Id 1 # Erhöhe den Zähler $mbxcount++ # Führe die Funktion aus und exportiere die Ergebnisse $alias=$null;$alias=$mbx.Alias $result = get-MailboxFolderPermissionsForAllFolders -mailbox $mbx if(test-path "MBXPerms\$alias.csv"){del "MBXPerms\$alias.csv"} $result | ?{$_.identity -ne "" -or $_.identity -ne $null} | select identity,FolderName,User,AccessRights,SharingPermissionFlags | Export-Csv -Path "MBXPerms\$alias.csv" -NoTypeInformation -Delimiter ";" -Encoding UTF8 -Append } Write-Progress -Activity $activity -Completed -Id 1 Write-Host "Processing complete." Write-host "This took $(((get-date)-$start).minutes) minutes and $(((get-date)-$start).seconds) seconds." Write-Host "Finished." -ForegroundColor Green Write-Host "`n" } #endregion MailboxFolderPermissions #endregion MailboxPermissionData #region MailboxStatisticsData #MailboxStatistics primäre MBX laden und exportieren Write-host "## Getting mailbox statistics data ###" -ForegroundColor Cyan $start=get-date write-host "Starting: $start" [array]$csvdata=@() $itemtotalcount=$Users.Count $itemcount=1 $now=get-date Write-host "Getting MBX statistics data for ALL users..." -NoNewline foreach($user in $users){ #Progressbar $activity = "Get-MailboxStatistics" $progress = $itemcount / $itemtotalcount *100 ; Write-Progress -Activity $activity -PercentComplete $progress -Status "$itemcount/$itemtotalcount - Processing [$($user.Alias)]" $itemcount++ $stats=Get-MailboxStatistics $user | select DisplayName,MailboxType,MailboxTypeDetail,Database,itemcount,TotalItemSize,@{Name="TotalItemSizeBytes";Expression={$_.TotalItemSize.Value.ToBytes()}},LastLoggedOnUserAccount,LastLogonTime $stats | Add-Member -MemberType NoteProperty -Name 'UserPrincipalName' -Value $user.UserPrincipalName $csvdata += $stats } Write-Progress -Activity $activity -PercentComplete $progress -Completed $csvdata | select UserPrincipalName,DisplayName,MailboxType,MailboxTypeDetail,Database,itemcount,TotalItemSize,@{Name="TotalItemSizeBytes";Expression={$_.TotalItemSize.Value.ToBytes()}},LastLoggedOnUserAccount,LastLogonTime | export-csv ($logpath+"\"+$kunde+"_MailboxStatistics.csv") -NoTypeInformation -Delimiter ";" -Encoding UTF8 Write-host "This took $(((get-date)-$start).minutes) minutes and $(((get-date)-$start).seconds) seconds." Write-Host "Finished." -ForegroundColor Green Write-Host "`n" #MailboxStatistics Archivmailbox laden und exportieren Write-host "## Getting Archive mailbox statistics data ###" -ForegroundColor Cyan $start=get-date write-host "Starting: $start" [array]$csvdata=@() $itemtotalcount=$Users.Count $itemcount=1 $now=get-date Write-host "Getting statistics for ALL users' archive MBX..." -NoNewline $archiveUsers = $users | ?{$_.ArchiveName} foreach($user in $archiveUsers){ #Progressbar $activity = "Get-MailboxStatistics (Archive MBX)" $progress = $itemcount / $itemtotalcount *100 ; Write-Progress -Activity $activity -PercentComplete $progress -Status "$itemcount/$itemtotalcount - Processing [$($user.Alias)]" $itemcount++ $stats=Get-MailboxStatistics $user -Archive | select DisplayName,MailboxType,MailboxTypeDetail,Database,itemcount,TotalItemSize,@{Name="TotalItemSizeBytes";Expression={$_.TotalItemSize.Value.ToBytes()}},LastLoggedOnUserAccount,LastLogonTime $stats | Add-Member -MemberType NoteProperty -Name 'UserPrincipalName' -Value $user.UserPrincipalName $csvdata += $stats } Write-Progress -Activity $activity -PercentComplete $progress -Completed $csvdata | select UserPrincipalName,DisplayName,MailboxType,MailboxTypeDetail,Database,itemcount,TotalItemSize,@{Name="TotalItemSizeBytes";Expression={$_.TotalItemSize.Value.ToBytes()}},LastLoggedOnUserAccount,LastLogonTime | export-csv ($logpath+"\"+$kunde+"_MailboxStatistics-ArchiveMBX.csv") -NoTypeInformation -Delimiter ";" -Encoding UTF8 Write-host "This took $(((get-date)-$start).minutes) minutes and $(((get-date)-$start).seconds) seconds." Write-Host "Finished." -ForegroundColor Green Write-Host "`n" #endregion #region PublicFolders Write-host "## Getting PublicFolders ##" -ForegroundColor Cyan $start=get-date write-host "Starting: $start" try{ $PF=Get-PublicFolder -Recurse -ResultSize Unlimited -ErrorAction Stop #$PF | Export-CliXML ($logpath+"\"+$kunde+"_PFStructure.xml") $PF | select Name,ParentPath | export-csv ($logpath+"\"+$kunde+"_PFStructure.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation $PFStats = Get-PublicFolderStatistics -ResultSize Unlimited #$PFStats | Export-CliXML ($logpath+"\"+$kunde+"_PFStatistics.xml") $PFStats | select name,itemcount,totalitemsize,LastModificationTime | export-csv ($logpath+"\"+$kunde+"_PFStatistics.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation # statt Example auf MS Seite diesen Befehl zum Sichern der PF permissions verwenden #$PF | Get-PublicFolderClientPermission | Select-Object Identity,User,@{Name="AccessRights";Expression={$_.AccessRights}} | Export-CliXML ($logpath+"\"+$kunde+"_PFPerms.xml") $PF | Get-PublicFolderClientPermission | Select-Object Identity,User,@{Name="AccessRights";Expression={$_.AccessRights}} | Export-csv ($logpath+"\"+$kunde+"_PFPerms.csv") -Encoding UTF8 -Delimiter ";" -NoTypeInformation Get-MailPublicFolder -ResultSize Unlimited | Export-CliXML ($logpath+"\"+$kunde+"_MEPF.xml") Get-MailPublicFolder | Get-ADPermission | ?{$_.ExtendedRights -like "*Send-As*"} | Export-CliXML ($logpath+"\"+$kunde+"_OnPrem_MailPFSendAs.xml") Get-MailPublicFolder | ?{$_.GrantSendOnBehalfTo -ne "$null"} | select name,GrantSendOnBehalfTo | Export-CliXML ($logpath+"\"+$kunde+"_MailPFSoB.xml") } catch{ if(-not $PF){ $out = "No public folders found." $out | out-file ($logpath+"\"+$kunde+"_PublicFolders.csv") -encoding utf8 Write-Host $out } else{ write-host "Caught an exception:" -ForegroundColor Red write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red } } Write-host "This took $(((get-date)-$start).minutes) minutes and $(((get-date)-$start).seconds) seconds." Write-Host "Finished." -ForegroundColor Green Write-Host "`n" #endregion #region mergedata #merge mailbox infos and mailbox statistic infos Write-host "## Performing final tasks ##" -ForegroundColor Cyan Write-Host "Merging data" # CSVs einlesen $mbxinfos = Import-Csv ($logpath + "\" + $kunde + "_Mailboxes.csv") -Delimiter ";" $mbxstatinfos = Import-Csv ($logpath + "\" + $kunde + "_MailboxStatistics.csv") -Delimiter ";" $arcmbxstatinfos = Import-Csv ($logpath + "\" + $kunde + "_MailboxStatistics-ArchiveMBX.csv") -Delimiter ";" # Hilfsfunktion: Bytes -> menschenlesbar (ähnlich Exchange-Anzeige) function Convert-BytesToSizeString { param( [Parameter(Mandatory=$true)] [long]$Bytes ) # Einfache 1024er-Skala, 2 Nachkommastellen $units = @("B","KB","MB","GB","TB","PB") $size = [double]$Bytes $unitIndex = 0 while ($size -ge 1024 -and $unitIndex -lt ($units.Count - 1)) { $size = $size / 1024 $unitIndex++ } # Fixe InvariantCulture-Formatierung mit Punkt, ohne Tausendertrennzeichen $sizeStr = [System.String]::Format([System.Globalization.CultureInfo]::InvariantCulture, "{0:0.##}", $size) return "$sizeStr $($units[$unitIndex])" } # Indexe nach userPrincipalName (Case-insensitive via .ToLower()) $statsIndex = @{} foreach ($s in $mbxstatinfos) { if ($null -ne $s.userPrincipalName) { $statsIndex[$s.userPrincipalName.ToLower()] = $s } } $arcStatsIndex = @{} foreach ($a in $arcmbxstatinfos) { if ($null -ne $a.userPrincipalName) { $arcStatsIndex[$a.userPrincipalName.ToLower()] = $a } } # Merge: Mailbox + (Primär)Statistik + (Archiv)Statistik in ein Objekt $merged = foreach ($m in $mbxinfos) { $key = if ($m.userPrincipalName) { $m.userPrincipalName.ToLower() } else { "" } $stat = $null $arcStat = $null if ($key -ne "") { if ($statsIndex.ContainsKey($key)) { $stat = $statsIndex[$key] } if ($arcStatsIndex.ContainsKey($key)) { $arcStat = $arcStatsIndex[$key] } } # Basiseigenschaften vom Mailbox-Objekt $props = @{} foreach ($p in $m.PSObject.Properties.Name) { $props[$p] = $m.$p } # Alle Properties aus Primär-Statistik hinzufügen (ohne Duplikate) if ($null -ne $stat) { foreach ($p in $stat.PSObject.Properties.Name) { if (-not $props.ContainsKey($p)) { $props[$p] = $stat.$p } } } # --- Summenbildung für ItemCount & TotalItemSizeBytes (Primär + Archiv) --- # Robust parsen (leere oder nichtnumerische Werte => 0) $primItemCount = 0 $primSizeBytes = 0 $arcItemCount = 0 $arcSizeBytes = 0 if ($null -ne $stat) { if ($stat.PSObject.Properties.Match('ItemCount').Count -gt 0 -and [string]::IsNullOrWhiteSpace($stat.ItemCount) -eq $false) { [void][int64]::TryParse(($stat.ItemCount -replace '[^0-9\-]',''), [ref]$primItemCount) } if ($stat.PSObject.Properties.Match('TotalItemSizeBytes').Count -gt 0 -and [string]::IsNullOrWhiteSpace($stat.TotalItemSizeBytes) -eq $false) { [void][int64]::TryParse(($stat.TotalItemSizeBytes -replace '[^0-9\-]',''), [ref]$primSizeBytes) } } if ($null -ne $arcStat) { if ($arcStat.PSObject.Properties.Match('ItemCount').Count -gt 0 -and [string]::IsNullOrWhiteSpace($arcStat.ItemCount) -eq $false) { [void][int64]::TryParse(($arcStat.ItemCount -replace '[^0-9\-]',''), [ref]$arcItemCount) } if ($arcStat.PSObject.Properties.Match('TotalItemSizeBytes').Count -gt 0 -and [string]::IsNullOrWhiteSpace($arcStat.TotalItemSizeBytes) -eq $false) { [void][int64]::TryParse(($arcStat.TotalItemSizeBytes -replace '[^0-9\-]',''), [ref]$arcSizeBytes) } } $sumItemCount = ($primItemCount + $arcItemCount) $sumBytes = ($primSizeBytes + $arcSizeBytes) # In das Ausgabobjekt schreiben: # - TotalItemSizeBytes: Summe # - ItemCount: Summe # - TotalItemSize: neu aus Bytes berechnet (menschenlesbar) $props['CombinedItemCount'] = $sumItemCount $props['CombinedItemSizeBytes'] = $sumBytes $props['CombinedItemSize'] = Convert-BytesToSizeString -Bytes $sumBytes # Falls du zusätzlich die Originalwerte behalten willst (optional), hier Beispiele: #$props['Primary_ItemCount'] = $primItemCount #$props['Primary_TotalItemSizeBytes'] = $primSizeBytes $props['Archive_ItemCount'] = $arcItemCount $props['Archive_ItemSizeBytes'] = $arcSizeBytes New-Object PSObject -Property $props } # Export als CSV $outFile = Join-Path $logpath ($kunde + "_MailboxesAndMailboxStatistics_Merged.csv") $merged | Export-Csv -Path $outFile -Delimiter ";" -NoTypeInformation -Encoding UTF8 -Force #Write-Host "Fertig: $outFile" #endregion mergedata # optional Write-Host "Calculating min, max, average Mailbox sizes" $mailboxStats = import-csv (".\" + $kunde + "_MailboxesAndMailboxStatistics_Merged.csv") -Delimiter ';' # Calculate the average mailbox size (in MB) $measure = $mailboxStats | Measure-Object -Property CombinedItemSizeBytes -Sum -Average -Maximum -Minimum $sumBytes = [double]$measure.Sum $avgBytes = [double]$measure.Average $maxBytes = [double]$measure.Maximum $minBytes = [double]$measure.Minimum $result = [PSCustomObject]@{ Count = $measure.count Min_GB = "{0:N2}" -f ($minBytes / 1GB) Max_GB = "{0:N2}" -f ($maxBytes / 1GB) Sum_GB = "{0:N2}" -f ($sumBytes / 1GB) Avg_GB = "{0:N2}" -f ($avgBytes / 1GB) Min_MB = "{0:N2}" -f ($minBytes / 1MB) Max_MB = "{0:N2}" -f ($maxBytes / 1MB) Sum_MB = "{0:N2}" -f ($sumBytes / 1MB) Avg_MB = "{0:N2}" -f ($avgBytes / 1MB) Min_B = "{0:N2}" -f ($minBytes) Max_B = "{0:N2}" -f ($maxBytes) Sum_B = "{0:N2}" -f ($sumBytes) Avg_B = "{0:N2}" -f ($avgBytes) } $outFile = Join-Path $logpath ($kunde + "_MailboxesSizeSummary.txt") $result | out-file $outfile -Force Write-Host "Finished." -ForegroundColor Green Write-Host "`n"