Mailbox Size reports for Exchange Server using PowerShell - powershell

I'm using the following code to get a report of our exchange mailboxes sizes and usage
the output of this script shows on CSV file this columns:
DisplayName, FreeSpace, TotalItemSize, alias, IssueWarningQuota, ProhibitsendReceiveQuota ProhibitSendQuota
my questions are:
all these columns except for the FreeSpace shows the size in bytes for example: 2.784 GB (2,988,883,006 bytes)
i want these columns: TotalItemSize, IssueWarningQuota, ProhibitsendReceiveQuota, ProhibitSendQuota to show only the number without GB and the full bytes size like the FreeSpace column
add new column FreeSpace % that will calculate the free space for the mailbox.
Thanks !
# Load Exchange Management Shell in PowerShell ISE
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn
# Delete csv file on "C:\script"
Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails SharedMailbox | Get-MailboxStatistics |
Select DisplayName, #{n="Total Size (MB)";e={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}}, StorageLimitStatus
$Result=#()
#Get all user mailboxes
$mailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox
#Get all shared mailboxes
#$mailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails SharedMailbox
$totalmbx = $mailboxes.Count
$i = 0
$mailboxes | ForEach-Object {
$mbx = $_
#Get mailbox statistics
$mbs = Get-MailboxStatistics -Identity $mbx.Identity
$i++
Write-Progress -activity "Processing $mbx" -status "$i out of $totalmbx completed"
if ($mbs.TotalItemSize -ne $null){
$size = [math]::Round(($mbs.TotalItemSize.ToString().Split('(')[1].Split(' ')[0].Replace(',','')/1MB),2)
}else{
$size = 0 }
$Result += New-Object -TypeName PSObject -Property $([ordered]#{
Name = $mbx.DisplayName
PrimarySmtpAddress = $mbx.PrimarySmtpAddress
AliasSmtpAddresses = ($mbx.EmailAddresses | Where-Object {$_ -clike 'smtp:*'} | ForEach-Object {$_ -replace 'smtp:',''}) -join ';'
TotalSizeInMB = $size
SizeWarningQuota=$mbx.IssueWarningQuota
StorageSizeLimit = $mbx.ProhibitSendQuota
StorageLimitStatus = $mbs.ProhibitSendQuota
})
}
$Result | Export-CSV "C:\Temp\MailboxSizeReport.csv" -NoTypeInformation -Encoding UTF8
$results = ForEach($mb in $mailboxes){
$stats=get-mailboxstatistics $mb
if ($mb.ProhibitSendQuota -eq 'Unlimited') {
$freespace = 'Unlimited'
}
else {
$totalBytes = [double]($stats.totalitemsize -replace '.*?\((.*?) bytes.*','$1')
$prohibitBytes = [double]($mb.ProhibitSendQuota -replace '.*?\((.*?) bytes.*','$1')
$freespace = [Math]::Round(($prohibitBytes - $totalbytes)/1GB,2)
}
$props=#{
alias=$mb.alias
DisplayName=$mb.displayname
#StorageLimitStatus=$stats.StorageLimitStatus
TotalItemSize=$stats.totalitemsize
#DatabaseName=$stats.databasename
ProhibitSendQuota=$mb.ProhibitSendQuota
ProhibitsendReceiveQuota=$mb.ProhibitsendReceiveQuota
IssueWarningQuota=$mb.IssueWarningQuota
FreeSpace=$freespace
}
[pscustomobject]$props
}
$results | Sort-Object TotalItemSize -descending | export-csv c:\script\report.csv -NoTypeInformation -Encoding UTF8

Related

Powershell memory usage in runspacepool

i have a problem with code:
Measure-Command{ $controller=Get-ADDomainController -Filter *| Select -ExpandProperty Hostname
$users=Get-ADUser -Filter * |select samaccountname
$scriptblock={
param($samacc,$controller)
$result=#()
foreach($cont in $controller){
$RESULT=$result + (Get-ADUser -Server $cont -Identity $samacc -Properties lastlogon,whenchanged,displayname,title,company | sort-object lastLogon -descending | select-object enabled,displayname,samaccountname,title,company, #{Name="lastLogon";Expression={[datetime]::FromFileTime($_.'lastLogon')}},whenchanged)
}
$result|Sort-Object -Descending -Property LastLogon|select -First 1
}
$MaxThreads = 5
$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)
$RunspacePool.ApartmentState = "MTA"
$job=#()
$RunspacePool.open()
foreach($user in $users){
$PowerShell = [powershell]::Create().AddScript($scriptblock).AddArgument($user.samaccountname).AddArgument($controller)
$PowerShell.RunspacePool = $RunspacePool
$job+=[PSCustomObject]#{
Id = $_
Pipe = $PowerShell
Handle = $PowerShell.BeginInvoke()
Object = $Object
}
}
while ($job.Handle -ne $null){
$Completed = $job | Where-Object { $_.Handle.IsCompleted -eq $true }
foreach ($Runspace in $Completed){
$data=$Runspace.Pipe.EndInvoke($Runspace.Handle)
$data|Export-Csv d:\fulllist.csv -Append -Delimiter ';' -Encoding UTF8 -NoTypeInformation
$Runspace.Handle = $null
}
Start-Sleep -Milliseconds 100
}
$PowerShell.Dispose()
$RunspacePool.Dispose()
Remove-Variable controller,users,scriptblock,job,Completed,data,Runspace,RunspacePool,PowerShell
[System.GC]::Collect()
}
I create for each user instance with powershell command, and throw it to runspacepool. But i have about 35000 users and when i reach about 18000 for me start problem with connection\session. And to result table get only data for 22000 users. Powershell then dont free memory. How can i correctly manage close instances to free memory (for users that already write to file).May be i use wrong place for commands or wrong commands.

combine get-user get-mailboxstatistics exchange 2010

I need to create a report for exchange server 2010.
Where I need the users Display name, lastlogontime and account status ie enabled or disable.
get-mailbox statistics shows lastlogon and get-user can show account control status.
So I tried this not working anyhow.
Get-User -ResultSize Unlimited | Where { $_.RecipientType -eq ‘UserMailbox’ } | ForEach { $Users = #{} } { $Users[$_.SamAccountName] = $_ }
get-mailboxstatistics -server 00-exchbx01 |
ForEach {
New-Object psobject |
Add-Member -PassThru NoteProperty name $_.name |
Add-Member -PassThru NoteProperty lastlogontime $_.lastlogontime |
Add-Member -PassThru NoteProperty UserAccountControl $Users[$_.SamAccountName].UserAccountControl
} |select name,lastlogontime,useraccountcontrol |sort-lastlogontime -descending | export-csv c:\ussersxx.csv -nti
also tried No luck Yet any Help?
Get-User -ResultSize Unlimited | Where { $_.RecipientType -eq ‘UserMailbox’ } | ForEach { $Users = #{} } { $Users[$_.SamAccountName] = $_ } | get-mailboxstatistics -server 00-exchbx01 | select Name,useraccountcontrol, lastlogontime|sort-lastlogontime -descending | Export-csv c:\report.csv
`
This should do it.
$outtbl = #()
$users = Get-User -ResultSize Unlimited | Where { $_.RecipientType -eq ‘UserMailbox’ }
$users | % {
$x = Get-MailboxStatistics $_ | Select LastLogonTime
$t = New-Object PSObject -Property #{
Name = $_.Name
LastLogonTime = $x.LastLogontime
UserAccountControl = $_.UserAccountControl
}
$outtbl += $t
}
This is the way I've always done these "combining results of different commands" type scenarios.
You can then do $outtbl | Sort LastLogonTime -Descending | Export-Csv c:\ussersxx.csv -nti to export the data
There's a couple of things here, most of that looks fine except for your last line:
||sort-lastlogontime -descending |
This should become:
| sort -property lastlogontime -descending |
What you'll also run into is that you might end up with things coming down the pipeline from Get-MailboxStatistics that aren't in your $Users hash table. This will results in getting errors when using your hash table to fill out a property the psobject.
You could adjust this to iterate through the hash table, passing the SamAccountName as the value for the Identity property (but this will likely be slower), or add in some error handling so that you just end up with an empty property rather than it completely erroring out.

How do I show the value of LastLogonTime from a mailbox query

How can I show the value of the attribute LastLogonTime?
function Get-MailboxesNotLoggedOnTo {
param(
[int]$days = 90
)
$mailboxes = Get-Mailbox -ResultSize 500
$mailboxes | Where-Object {
(Get-MailboxStatistics $_).LastLogonTime -and
(Get-MailboxStatistics $_).LastLogonTime -le (Get-Date).AddDays(-$days)
} | FT DisplayName, Alias, ServerName, LastLogonTime
}
This is happening because Get-Mailbox does not return a property called LastLogonTime. Get-MailboxStatistics does. What you need to do is add the timestamp as a property of your output
$mailboxes = Get-Mailbox -ResultSize 200
$mailboxes | Where-Object {
(Get-MailboxStatistics $_).LastLogonTime -and
(Get-MailboxStatistics $_).LastLogonTime -le (Get-Date).AddDays(-$days)
} | ForEach-Object {Add-Member -InputObject $_ -MemberType NoteProperty -Name LastLogonTime -Value (Get-MailboxStatistics $_).LastLogonTime -PassThru} |
Select DisplayName, Alias, ServerName, LastLogonTime
Using Add-Member we can fill in the missing piece. The one issue I have with this is the multiple calls to Get-MailboxStatistics which im working on improving now. Should be something closer to this.
$checkDate = (Get-Date).AddDays(-90)
$mailboxes = Get-Mailbox -ResultSize 200
$mailboxes | ForEach-Object{
$stats = Get-MailboxStatistics $_
If ($stats.LastLogonTime -and ($stats.LastLogonTime -le $checkDate)){
Add-Member -InputObject $_ -MemberType NoteProperty -Name LastLogonTime -Value $stats.LastLogonTime -PassThru
}
} | Select DisplayName, Alias, ServerName, LastLogonTime
The extra calls to Get-MailboxStatistics would make it slower. Reduced the call to only the one. Still using Add-Member with -PassThru which just pipes out to a select statement. This should be a more efficient approach.

Find next available computer name

I'm trying to find the next available computer name in out domain. Our computers use a naming format
departmentName001
departmentName003
departmentName004
...
departmentName999
I can find the existing computer accounts and add 1 but I can't work out for to get it to start looking at 001, I'm aware of the use of "{0:d3}" -f but I'm not using it correctly. Can anyone help?
function GetComputerList($ComputerName)
{
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = “LDAP://dc=domain,dc=local”
$objSearcher.Filter = ("(&(objectCategory=computer)(name=$ComputerName))")
$colProplist = "name"
$objSearcher.PageSize = 1000
foreach ($i in $colPropList){[void]$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults)
{$objComputer = $objResult.Properties; $objComputer.name}
}
$HostName = Finance
$unit="{0:d3}" -f $_
$num = GetComputerList("$HostName*") | Foreach {[int]($_.Name)} | Sort-Object | Select-Object -Last 1
$name = $HostName+($unit+($num+1))
Try this, it gets all computer with name starting with 'departmentName', strips all a-z characters, leaving just the numbers, converts the numbers to integers and sorting them to find the largest one:
$searcher = [ADSISearcher]'(&(objectCategory=computer)(name=departmentName*))'
$searcher.PageSize = 1000
$last = $searcher.FindAll() | Foreach-Object { [int]($_.Properties.name -replace '\D').Trim() } | Sort-Object | Select-Object -Last 1
$digitLength = "$last".Length
$NewComputerName = "{0}{1:D$digitLength}" -f 'departmentName',($last+1)
$NewComputerName
EDIT:
# get next available number in a range of numbers. returns 5 for 1,2,3,4,6,7,9
$number = $searcher.FindAll() | Foreach-Object { [int]($_.Properties.name -replace '\D').Trim() } | Sort-Object
for($i=0; $i -lt $number.length; $i++) {if( $number[$i+1]-$number[$i] -gt 1) {$number[$i]+1; break} }
try this:
$searcher = [ADSISearcher]'(&(objectCategory=computer)(name=Finance*))'
$searcher.PageSize = 1000
$last = $searcher.FindAll() | Foreach-Object {
[string]($_.Properties.name -replace '\D') } | Sort-Object
$i = 0
$last | % { if ($i -ne [int]$_ ) { $new = $i.tostring().padleft(3,'0'); break }
else
{ $i++ }}
$newComputerName = "finance" + $new
based on the information in this post I have made a few changes and tweaks to the code for my environment to check more than just AD.. and also fixed it not filling in blanks at the start of a range.. I have blogged it here: AutoGeneratingServer Names
copy of the code here too, and I know it can be refactored lots!
[CmdletBinding()]
param()
# ********************************************************
$startOfName = "xxxYYYZZWEB"
# ********************************************************
# VMWare Details
$ADVIServers = #("vsphere1.blah.local","vsphere2.blah.local","vsphere3.blah.local","vsphere4.blah.local")
$StandAloneHosts = #()
# DNS Details
$DNSServer = "xxxxxx.blah.local"
# SCCM 2012 Details
$SCCM2012SiteServer = "sccm2012.blah.local"
$SCCM2012SiteCode = 'SiteCode'
# SCCM 2007 Details
$SCCM2007SiteServer = "sccm2007.blah.local"
$SCCM2007SiteCode = 'SiteCode2'
# SCOM 2007 Details
$SCOMServer = "scom.blah.local"
# Create Empty Arrays
$VMNumbers = #()
$ADnumbers = #()
$DNSNumbers = #()
$SCCM2012Numbers = #()
$SCCM2007Numbers = #()
$SCOM2007Numbers = #()
# VMWare
Write-Verbose "Processing VMware"
Add-PSSnapin vmware.vimautomation.core -ErrorAction SilentlyContinue
# Set options for certificates and connecting to multiple enviroments
$null = Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$False
$null = Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope User -Confirm:$False
# Connect to each AD Authenticated viServer
foreach ($VIServer in $ADVIServers){$null = Connect-VIServer $VIServer -verbose:$false}
# Connect to standalone host
foreach ($Host in $StandAloneHosts){$null = Connect-VIServer $Host -User 'usernamehere' -Password 'passwordhere' -verbose:$false}
# get next available number in a range of numbers.
$VMNames = Get-VM -Name "$($startOfName)*" -verbose:$false |select Name
$VMNames |select Name | Foreach-Object {Write-Verbose $_.Name} | Sort-Object
$VMNumbers = $VMNames |select Name | Foreach-Object {[int]($_.Name -replace '\D').Trim() } | Sort-Object
Write-Verbose "$($VMNumbers.Count) Matching entries found"
# Active Directory
Write-Verbose "Processing Active Directory"
# Issue Query
$searcher = [ADSISearcher]"(&(objectCategory=computer)(name=$($StartOfName)*))"
$searcher.PageSize = 1000
# get next available number in a range of numbers. returns 5 for 1,2,3,4,6,7,9 From AD
$ADNames = $searcher.FindAll() | Foreach-Object {[string]$_.Properties.name} | Sort-Object
$ADNames | Foreach-Object {Write-Verbose $_} | Sort-Object
$ADnumbers = $ADNames | Foreach-Object {[int]($_ -replace '\D').Trim() } | Sort-Object
Write-Verbose "$($ADnumbers.Count) Matching entries found"
# Search DNS
Write-Verbose "Processing DNS"
# Import DNS module
Import-Module dnsShell -Verbose:$false
$DNSNames = get-dnsRecord -server $DNSServer -RecordType A -Zone blah.local | select Name |where {$_.Name -like "$($startOfName)*"}
$DNSNames | Foreach-Object {Write-Verbose $_.Name} | Sort-Object -Unique
$DNSNumbers = $DNSNames | Foreach-Object {[int]($_.Name -replace '\D').Trim() } | Sort-Object -Unique
Write-Verbose "$($DNSNumbers.Count) Matching entries found"
# Search SCCM
Write-Verbose "Processing SCCM 2012"
# Query SCCM2012 Env
$SCCM2012Members = Get-WmiObject -ComputerName $SCCM2012SiteServer -Namespace "ROOT\SMS\site_$SCCM2012SiteCode" -Query "SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID='SMS00001' AND Name LIKE '$($startOfName)%' order by name" | select Name -Unique
$SCCM2012Members |select Name | Foreach-Object {Write-Verbose $_.Name} | Sort-Object
$SCCM2012Numbers = $SCCM2012Members |select Name | Foreach-Object {[int]($_.Name -replace '\D').Trim() } | Sort-Object
Write-Verbose "$($SCCM2012Numbers.Count) Matching entries found"
Write-Verbose "Processing SCCM 2007"
# Query SCCM2007 Env
$SCCM2007Names = Get-WMIObject -ComputerName $SCCM2007SiteServer -Namespace "root\sms\site_$SCCM2007SiteCode" -class "SMS_R_System" -filter "Name LIKE `"$startOfName%`"" |select Name | Sort-Object -Property Name -Unique
$SCCM2007Names |select Name | Foreach-Object {Write-Verbose $_.Name} | Sort-Object
$SCCM2007Numbers = $SCCM2007Names |select Name | Foreach-Object {[int]($_.Name -replace '\D').Trim() } | Sort-Object
Write-Verbose "$($SCCM2007Numbers.Count) Matching entries found"
# Search Production SCOM 2007
Write-Verbose "Processing SCOM 2007"
#Initialize SCOM SnapIn
Add-PSSnapin Microsoft.EnterpriseManagement.OperationsManager.Client -ErrorAction SilentlyContinue -verbose:$false
#Connect to Production SCOM 2007 Env.
$null = New-ManagementGroupConnection -ConnectionString $SCOMServer
#Connect to SCOM Provider
Push-Location 'OperationsManagerMonitoring::'
# Get Agents Matching Name
$SCOM2007Names = Get-ManagementServer |Get-Agent |Where {$_.Name -like "$($startOfName)*"}
$SCOM2007Names | Foreach-Object {Write-Verbose $_.Name} | Sort-Object
$SCOM2007Numbers = $SCOM2007Names | Foreach-Object {[int]($_.Name -replace '\D').Trim() } | Sort-Object
Write-Verbose "$($SCOM2007Numbers.Count) Matching entries found"
# Return to previous location
Pop-Location
# Merge arrays adding a zero so we allways start issuing numbers from the beginning (ie 001)
$list = #(0) + $VMNumbers + $ADnumbers + $DNSNumbers + $SCCM2012Numbers + $SCCM2007Numbers + $SCOM2007Numbers
# Remove Duplicates numbers from the array and sort into numerical order
$list = $list | Sort-Object -Unique
Write-Verbose "Used numbers after sorting: $($list)"
# Determine if next server name is a gap in the sequence in the array
for($i=0; $i -lt $list.length; $i++) {
if( $list[$i+1]-$list[$i] -gt 1) {
# The gap between the current server number and the next element in the array is greater than 1
# So we have an available number we can use.
# TODO: - Add support for consecutive numbers IE build 6 servers with consecutive numbers.
$num = "{0:000}" -f ($list[$i]+1)
break
}
}
# If no gap found in the sequence then use the next number from the sequence in the array
if ($num -eq $null) {
$num = "{0:000}" -f (($list[-1]+1))
}
# Construct new name
$NewComputerName = "{0}{1}" -f $startOfName,$num
# Create DNS Record to 'reserve / mark the name as in use'
Write-Verbose "Creating DNS Reservation"
New-DnsRecord -Name $NewComputerName -IPAddress "127.0.0.1" -Zone blah.local -Type A -Server $DNSServer
write-output $NewComputerName

Exchange - listing mailboxes in an OU with their mailbox size

I'm trying to display all the mailboxes and their sizes for all our users in our Departed OU. I seem to be very close but my command seems to be adding some padding to the results.
[PS] C:\Windows\system32>dsquery user "ou=Departed,ou=Staff,dc=COMPANY,dc=local" -limit 4 | dsget user -samid | Get-MailboxStatistics | ft DisplayName, TotalItemSize, ItemCount
And the output:
Dsquery has reached the specified limit on number of results to display; use a different value for the -limit option to
display more results.The specified mailbox " samid " doesn't exist.
+ CategoryInfo : NotSpecified: (0:Int32) [Get-MailboxStatistics], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : DD7D7CEA,Microsoft.Exchange.Management.MapiTasks.GetMailboxStatistics
The specified mailbox " Eka.Tian " doesn't exist.
+ CategoryInfo : NotSpecified: (1:Int32) [Get-MailboxStatistics], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : 7F701DFD,Microsoft.Exchange.Management.MapiTasks.GetMailboxStatistics
Obviously shouldnt work for the first result "samid" but "Eka.Tian" exists. Why is it adding all those spaces? Is there a way I could format the output from dsget user so it plays nice with Get-MailboxStatistics?
Why the dsquery?
get-mailbox -OrganizationalUnit "ou=Departed,ou=Staff,dc=COMPANY,dc=local" -resultsize unlimited |
get-mailboxstatistics | ft DisplayName,TotalItemSize,Itemcount
I've got something for you, even though it's a little late.
You just need to adjust every Searchbase with OU and DC, the Email-Adresses at the end and the SMTP-Server, then you get an Email with a CSV-Attachment that contains every OU with Counts of active and inactive Mailboxes and a list with every mailbox and its parameters.
You can also trigger it with the Task-Scheduler of Windows, so it's an automatic report.
Add-PSSnapin Microsoft.Exchange.Management.Powershell.SnapIn;
$Kunden=Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Kunden,DC=domain,DC=domain"
$leerzeile ="`n"
#Funktion für 10 GB Kontrolle
function getUber10 ($name)
{
$Uberschreit=0
$anzahluber10=0
$anzahl=0
$UserList = Get-Mailbox -OrganizationalUnit "$name" |Get-MailboxStatistics
$großen = $UserList |Select TotalItemSize
for($y=0; $y -lt $großen.Length; $y++){
if($großen[$y].totalItemSize.value.toMB() -gt 10000){
$wieoft=$großen[$y].totalItemSize.value.toMB() * 0.0001
$anzahluber10 = $anzahluber10 + [Math]::Ceiling($wieoft) - 1
}
}
$anzahluber10
}
#Liste aller Kunden mit Postfachanzahl
Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Kunden, DC=domain, DC=domain" |Select-Object Name, #{n="Postfach-Anzahl";e = {(Get-ADUser -Filter {(EmailAddress -like "*#*") -and (Enabled -eq "True")} -SearchBase $_).count}},`
#{n="Deaktivierte Postfächer";e = {(Get-ADUser -Filter {Enabled -eq "False"} -SearchBase $_).count}}, #{n="10GB-Überschreitungen"; e={ getUber10 -name $_}} `
| ConvertTo-Csv -Delimiter ";" -NoTypeInformation | % {$_.Replace('"','')} | Out-File C:\ExchangeReport.csv -Append
$leerzeile | Out-File C:\ExchangeReport.csv -Append
$leerzeile | Out-File C:\ExchangeReport.csv -Append
#Liste der einzelnen Kunden mit Details der Postfächer
For($i=1; $i -lt $Kunden.Length; $i++){
$Kunde=$Kunden[$i]
$Uberschreit=0
$anzahluber10=0
$anzahl=0
$UserList = Get-Mailbox -OrganizationalUnit "$Kunde" |Get-MailboxStatistics
$großen = $UserList |Select TotalItemSize
for($x=0; $x -lt $großen.Length; $x++){
if($großen[$x].totalItemSize.value.toMB() -gt 10000){
$wieoft=$großen[$x].totalItemSize.value.toMB() * 0.0001
$anzahluber10 = $anzahluber10 + [Math]::Ceiling($wieoft) - 1
}
}
Get-ADOrganizationalUnit -Identity $Kunden[$i] |Select-Object Name, #{n="Postfach-Anzahl";e = {(Get-ADUser -Filter {(EmailAddress -like "*#*") -and (Enabled -eq "True")} -SearchBase $Kunde).count}}`
,#{n="Deaktivierte Postfächer";e = {(Get-ADUser -Filter {Enabled -eq "False"} -SearchBase $_).count}},#{n="10GB-Überschreitungen"; e={$uberschreit= $anzahluber10 ; $uberschreit}}`
| ConvertTo-Csv -Delimiter ";" -NoTypeInformation | % {$_.Replace('"','')} | Out-File C:\ExchangeReport.csv -Append
Get-Mailbox -OrganizationalUnit "$Kunde" |Select-Object #{n="Kundenname";e={Get-ADOrganizationalUnit -Identity $Kunden[$i] |Select-Object Name}}, Displayname, PrimarySmtpAddress, `
#{n="Size(MB)";e = {$Fachstat = Get-MailboxStatistics $_.name;$Fachstat.totalItemsize.value.toMB()}}, #{n="Quota";e={$Fachquot=Get-Mailbox $_.name;$Fachquot.ProhibitSendReceiveQuota}},`
#{n="Aktiv?"; e={Get-ADUser $_.DistinguishedName |select Enabled}}, #{n="Über 10GB?"; e={$uber10 = Get-MailboxStatistics $_.name; if($uber10.totalItemSize.value.toMB() -gt 10000){$uber10.IsValid}else{$uber10.IsQuarantined}}} `
| ConvertTo-Csv -Delimiter ";" -NoTypeInformation | % {$_.Replace('"','')} | % {$_.Replace('#{Name=','')} | % {$_.Replace('}','')} | % {$_.Replace('#{Enabled=','')} | Out-File C:\ExchangeReport.csv -Append
$leerzeile | Out-File C:\ExchangeReport.csv -Append
$leerzeile | Out-File C:\ExchangeReport.csv -Append
}
$Date = Get-DAte -UFormat "%d.%m.%Y"
Send-MailMessage -to "empfänger#domain.domain" -from "administrator#domain.domain" -Subject "Exchange-Report" -body "Exchange Report of $Date" -SmtpServer "External IP" -Attachments "C:\ExchangeReport.csv"
Remove-Item C:\ExchangeReport.csv
I wrote the variables etc. in German, I hope thats no problem ;)