EN 
06.12.2025 Mikuláš WELCOME IN MY WORLD

This website is originally written in the Czech language. Most content is machine (AI) translated into English. The translation may not be exact and may contain errors.

Tento článek si můžete zobrazit v originální české verzi. You can view this article in the original Czech version.
PowerShell - Exchange server

PowerShell - Exchange server

Edited 07.08.2013 16:10 | created | Petr Bouška - Samuraj |
Unlike Active Directory, MS Exchange Server 2007 had to use PowerShell for a number of operations right from the start. Some operations have been added to the Exchange Management Console GUI over time, but some we can only perform via PowerShell. So again my little pull of useful PowerShell cmdlets for Exchange server (so far in 2007 and 2010 versions).
displayed: 40 659x (39 593 CZ, 1 066 EN) | Comments [10]

General Properties

If we want to use PowerShell ISE, and not Exchange Management Shell, we must first load the Exchange server commands.

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin 

For Exchange Server 2010, we can use.

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

Another option is to connect remotely to Exchange PowerShell. Either we let a dialog be displayed for entering the username and password, and use them for the connection.

$user = Get-Credential 
$ExchSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI https://mail.firm.local/powershell -Credential $user 
Import-PSSession $ExchSession
# Exchange commands
Remove-PsSession $ExchSession

Or we can use the details of the currently logged-in user (under which we're running the script).

$ExchSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI https://mail.firm.local/powershell -Authentication Kerberos
Import-PSSession $ExchSession
# Exchange commands
Remove-PsSession $ExchSession

Users and Mailboxes

Creating a User with a Mailbox

We create the user with the default password 123456 and specify the container in which the account will be created.

$pass = ConvertTo-SecureString -AsPlainText -Force -String '123456' 
New-Mailbox -Name 'Petr Bouška' -Alias 'bouska' -OrganizationalUnit 'firm.local/Firm -UserPrincipalName 'bouska@firm.local' -SamAccountName 'bouska' -FirstName 'Petr' -LastName 'Bouška' -Password $pass -ResetPasswordOnNextLogon $false -Database 'MAIL\First Storage Group\Mailbox Database' -ActiveSyncMailboxPolicy 'Default' 

Mailbox Information

Get-Mailbox -Identity bouska | FL 

Setting AutoAccept for Calendar Events

For example, for a conference room, we want it to automatically approve reservations. The important parameter is BookingWindowInDays, which determines how long (recurring) an event we can set.

Set-MailboxCalendarSettings -Identity conference-room -BookingWindowInDays 360 -AutomateProcessing AutoAccept -AddOrganizerToSubject $false -DeleteSubject $false

Mailbox Permissions

Checking permissions

Get-MailboxPermission -Identity conference-room | FT -AutoSize

Setting permissions

Add-MailboxPermission -Identity conference-room -User bouska -AccessRights FullAccess -InheritanceType All

Removing permissions

Remove-MailboxPermission -Identity conference-room -User bouska -AccessRights FullAccess -InheritanceType All

Calendar Information

Get-MailboxCalendarSettings -Identity conference-room | FL 

Setting Calendar Delegation

Set-MailboxCalendarSettings -Identity conference-room -ResourceDelegates bouska -ForwardRequestsToDelegates $true

Setting Calendar Permissions

Add-MailboxFolderPermission -Identity whose-calendar:\Calendar -User who-we-grant-rights -AccessRights Reviewer

List of Databases

Get-MailboxDatabase

List of Mailboxes

Get-Mailbox
Get-Mailbox -Database SERVER\VIP  

List of All Email Addresses, Groups, and PFs (with a filter on part of the address)

Get-Mailbox -ResultSize unlimited | Select-Object DisplayName -ExpandProperty EmailAddresses | Where-Object {$_.SmtpAddress -like "*firm.cz*"} | FT displayName, SmtpAddress 
Get-DistributionGroup -ResultSize unlimited | Select-Object DisplayName -ExpandProperty EmailAddresses | Where-Object {$_.SmtpAddress -like "*firm.cz*"} | FT displayName, SmtpAddress
Get-MailPublicFolder -ResultSize unlimited | Select-Object DisplayName -ExpandProperty EmailAddresses | Where-Object {$_.SmtpAddress -like "*firm.cz*"} | FT displayName, SmtpAddress

List of All SMTP Addresses - Export to CSV

Get-Recipient -ResultSize unlimited | Select Name -ExpandProperty EmailAddresses | Select Name, SmtpAddress | Export-csv d:\AllEmailAddress.csv

Searching for Email Addresses Containing Text

Get-Recipient -ResultSize unlimited | Select Name -ExpandProperty EmailAddresses | Where-Object {$_.smtpAddress -like "*@firm.it"} | FT Name, SmtpAddress

List of Mailbox Sizes

Get-MailboxStatistics -Database SERVER\VIP
Get-MailboxStatistics -Server SERVER -Identity bouska
Get-MailboxStatistics | select DisplayName,TotalItemSize,ItemCount,LastLogonTime | sort TotalItemSize

Disabling POP3 and IMAP

Set-CASMailbox -Identity bouska -PopEnabled $false -imapEnabled $false 

List of Mailboxes with POP3 or IMAP Enabled

Get-CASMailbox -Filter {popEnabled -eq "True"}
Get-CASMailbox -Filter {imapEnabled -eq "True"} 

Setting IMAP and POP3 for a Mailbox

Users have POP3 and IMAP enabled by default. If we want to prevent this, we can only disable the services. But if we want to have IMAP enabled for a few selected accounts and disable it for the rest, this is not possible. One solution is to set an extended attribute, e.g., to the "IMAP" value for the special accounts, and disable it for all accounts that don't have this setting.

List of users who have the customAttribute1 set (in ADUC for the user, Attribute Editor tab, extensionAttribute1 item)

Get-Mailbox -Filter {customAttribute1 -eq "IMAP"}

Disable POP3 for all users who have it enabled

Get-CASMailbox -Filter {popEnabled -eq "True"} | Set-CASMailbox -PopEnabled $false 

Disable IMAP for all who don't have the attribute set

Get-CASMailbox -Filter {imapEnabled -eq "True"} | get-Mailbox | where{$_.customAttribute1 -ne "IMAP"} | Set-CASMailbox -imapEnabled $false

Changing the Size Limit on Rules and Alerts

A user can have only a limited number of active rules (Rules and Alerts) created in their mailbox. This limit is given by the total size that these rules occupy, and on Exchange 2007, it is 64 kB.

Set-Mailbox -Identity bouska -RulesQuota 128kB

Public Folders

Determining User Permissions on a Public Folder

Get-PublicFolderClientPermission -Server SERVER -Identity "\folders\hotline" 

Setting User Permissions on a Public Folder

Add-PublicFolderClientPermission -Identity "\folders\hotline" -AccessRights Owner -User bouska

Determining Permissions on an AD Object

Get-ADPermission -Identity hotline | FT -AutoSize

Setting SendAs Permissions

Add-ADPermission -Identity hotline -User bouska -ExtendedRights Send-as

List of Public Folder Sizes

Get-PublicFolderStatistics -Server SERVER -ResultSize Unlimited | Sort-Object TotalItemSize | FT Name,FolderPath,ItemCount,TotalItemSize,LastAccessTime -AutoSize

Size of a Specific Public Folder with Subfolders

Get-PublicFolder "\Folder1\Folder2" -Recurse | Get-PublicFolderStatistics -Server SERVER -ResultSize Unlimited | ForEach-Object {$_.TotalItemSize.Value.ToMB()} | Measure-Object -Sum

Additional Statistics

Get-PublicFolderStatistics -Server SERVER -ResultSize Unlimited | FT Name, FolderPath, ItemCount, @{label='TotalItemSize(KB)';Expression={$_.TotalItemSize.Value.ToKB()}} 
Get-PublicFolderStatistics -Server SERVER -ResultSize Unlimited | ForEach-Object {$_.TotalItemSize.Value.ToMB()} | Measure-Object -Sum
Get-PublicFolderStatistics -Server SERVER -ResultSize Unlimited | Measure-Object -Sum -Property ItemCount

List of Public Folders, Their File Size, and Available Space

The AvailableNewMailboxSpace value shows how much space we can free up when we perform an Offline Defrag.

Get-PublicFolderDatabase -Status | FT Name, DatabaseSize, AvailableNewMailboxSpace

Address Lists

List of All Address Lists

Get-AddressList

Renaming an Address List

Changing the name and display name of the list. We can change the name through the GUI, but we won't change the DisplayName there, so users in Outlook will still see the old name.

Set-AddressList -Identity "All Users " -Name "Employees"
Set-AddressList -Identity "Employees" -DisplayName "Employees"

Messages and Logs (email)

Administrator Audit Log

From Exchange 2010 SP1, a log of every administrative intervention is stored in a special arbitration mailbox. We can retrieve information from it using two cmdlets or the ECP.

We can simply display the use of a particular cmdlet.

Search-AdminAuditLog -Cmdlets New-Mailbox

Or we can have the query result sent to us by email in XML format.

New-AdminAuditLogSearch -Name "Mailbox change log" -Cmdlets New-Mailbox, Set-Mailbox -StatusMailRecipients bouska@oksystem.cz -StartDate 11/01/2013 -EndDate 11/30/2013

Finding Specific Messages Over a Given Period

We need to find out if a message was received on a particular address in the last day, or we want to list all incoming messages from a particular sender - there are many similar situations. We will use the Get-MessageTrackingLog cmdlet, which, as the name suggests, goes through the message tracking log and searches for specific records. We can specify the category (such as Receive, Send), sender, recipient, time range, subject (if we're logging it), etc.

Get-MessageTrackingLog -server MAIL1 -EventID "RECEIVE" -Recipients "samuraj@samuraj-cz.com" -Start "01/12/2010 00:00:00" -End "03/12/2010 23:59:59" | Group Recipients | FL
Get-MessageTrackingLog -server MAIL1 -EventID "RECEIVE" -Sender "samuraj@samuraj-cz.com" -Recipients "samuraj@samuraj-cz.com" -MessageSubject "question" -Start "06/12/2010 16:00:00" -End "06/12/2010 17:00:00" | FT Timestamp, Sender, MessageSubject -AutoSize

If we want to find out if a message was received in the last hour, we can use the following, for example.

$time = Get-Date
$mails = Get-MessageTrackingLog -server OKMAIL1 -EventID "RECEIVE" -Sender "samuraj@samuraj-cz.com" -Recipients "samuraj@samuraj-cz.com" -Start $time.AddHours(-1) -End $time |  FT Timestamp, Sender, MessageSubject -AutoSize
($mails | Measure-Object).Count

Statistics Over the Last Period

It may be helpful to get various statistical data from sent and received emails. For example, the top 10 addresses from which mail was sent in the last 12 hours.

Get-MessageTrackingLog -Start (Get-Date).AddHours(-12) -End (Get-Date) -ResultSize unlimited | group-object -Property Sender | Sort-Object Count -Descending | Select -First 10 | FT Count, Name

Or similarly, the number of messages sent from an address in the last hour.

Get-MessageTrackingLog -Start (Get-Date).AddHours(-1) -End (Get-Date) -ResultSize unlimited | group-object -Property Sender | FT Count, Name

Another similar example is the number of messages for a recipient over a given period.

Get-MessageTrackingLog -Start "8/6/2013 08:00:00" -End "8/6/2013 10:00:00" -ResultSize unlimited | Select-Object -ExpandProperty Recipients | Group-Object | FT Count, Name

Or a list of messages larger than 1MB in the last hour.

Get-MessageTrackingLog -Start (Get-Date).AddHours(-1) -End (Get-Date) -ResultSize unlimited  | Select-Object sender,recipients,totalbytes,eventid  | where {$_.totalbytes -gt "1000000"} 

Tests and Checks

Test ActiveSync connectivity for a specific user (we need to enter their password).

Test-ActiveSyncConnectivity -MailboxCredential (get-credential user@domain)

Test synchronization with the Edge server and verify if it has the current data.

Test-EdgeSynchronization

Verifies if email sending and delivery is working, can also test between defined mailbox servers and check for delays.

Test-Mailflow

Logs in to a defined or system mailbox, thus verifying the functionality of MAPI, LDAP, and the Exchange store.

Test-MAPIconnectivity

Verifies the autodiscover functionality.

Test-OutlookWebServices | FT -AutoSize

Verifies OWA functionality for a specific user (we need to enter their password).

Test-OwaConnectivity -MailboxCredential (get-credential user@domain)

Verifies POP3 functionality for a specific user (we need to enter their password).

Test-PopConnectivity -MailboxCredential (get-credential user@domain)

Checks if a given IP address is legitimate for sending emails from a given domain.

Test-SenderId -IPAddress 1.2.3.4 -PurportedResponsibleDomain domain.tld

Lists all Exchange services and tests whether they are running and set to autostart.

Test-ServiceHealth

Retrieves data about the Exchange system and prints recommendations based on Best Practices.

Test-SystemHealth
Author:

Related articles:

PowerShell

Articles related to Microsoft's PowerShell scripting language, which is used in all new versions of MS OS and applications.

Microsoft Exchange

Almost since the beginning of my practice, I have been involved in the administration of the Microsoft mail server, i.e. Exchange Server. I started with the 2003 version and worked my way up to Exchange Online. The articles cover many areas of management. Most since the migration to Exchange Server 2016 and its complete configuration. But also Exchange Hybrid and e-mail security.

If you want write something about this article use comments.

Comments
  1. [1] Piki

    Zdravim, jeste bych doplnil co jsem nedavno hledal:

    Pravidla pro trideni posty jsou defaultne nastaveny na velikost 32kb

    nastaveni na 256kb

    Set-Mailbox uzivatel@domena.tld -RulesQuota:256KB

    Saturday, 20.11.2010 13:53 | answer
  2. [2] Samuraj

    respond to [1]Piki: Díky za tip, doplním do seznamu. Nevěděl jsem, že se tento limit dá zvednout, to se hodí.

    Saturday, 20.11.2010 16:16 | answer
  3. [3] Vladimír Dlesk

    Zdravím pane Bouška, mám na Vás dotaz. Potřeboval bych k cca. 500 účtům v AD(2003)/Exchange 2003 přidat email alias s určitou novou doménou. Neřešil jste to někdy? Děkuji

    Wednesday, 09.03.2011 16:36 | answer
  4. [4] Samuraj

    respond to [3]Vladimír Dlesk: Jestli se nepletu, tak to se dělá běžně a jednoduše pomocí E-mail Address Policy (jestli se to na 2003 jmenuje stejně). Defaultní politiku tam máte už teď, ta přiřazuje defaultní doménu. A můžete přidat druhou, buď pro všechny uživatele nebo je vybrat podle nějakého parametru.

    Wednesday, 09.03.2011 16:41 | answer
  5. [5] Jiri

    Dobrý den,

    super článek jako vždy :-) , jen mi žel nejde na Exchange 2010 SP2 zobrazit či změnit nastavení pro kalendář:

    Get(Set)-MailboxFolderPermission -Identity jméno@doména:\Calendar -User komu-dáme-práva -AccessRights Reviewer

    bez parametru :\calendar se mi výsledek zobrazí.

    Píše to 'jméno@doména.local:\calendar' couldn't be found.

    Nesetkal jste se s tím prosím někdy?

    Moc děkuji

    Monday, 25.02.2013 14:33 | answer
  6. [6] Samuraj

    respond to [5]Jiri: Napadá mne, jestli se složka daného uživatele opravdu jmenuje Calendar a ne například Kalendář.

    Můžete si vypsat seznam jeho složek

    Get-MailboxFolderStatistics -Identity bouska | FT Identity

    Monday, 25.02.2013 15:41 | answer
  7. [7] Jiri

    respond to [6]Samuraj: Děkuji moc,

    mailbox:\kalendář funguje - nečekal jsem takovou češtinu :-)

    Wednesday, 13.03.2013 14:07 | answer
  8. [8] Milan

    Dobrý den,

    mohl bych požádat o radu?

    Mám Exchange 2010, provozujeme PublicFolders. U některých PF se stává, že při Odpovědět všem se vyplní všichni příjemci, ale odesílatel původní zprávy se nevyplní. Při použití jen Odpovědět se původní odesílatel vyplní. Děje se to jen u některých složek. Zkusil jsem ty problémové složky znovu založit, ale výsledek je stále stejný.

    Nevíte někdo kde by mohl být zakopaný pes? Nebo co udělat?

    Děkuji moc

    Milan

    vysin1@seznam.cz

    Monday, 14.07.2014 22:12 | answer
  9. [9] Milan

    respond to [8]Milan: problém jsem už vyřešil, atk kdyby náhodou měl podobný problém:

    Před exchangem je ještě Kerio mail server a tam bylo chybně nastaveno reply-to, jinak tento údaj v hlavičce chybí

    a exchange pak odesilatele ignoruje

    Milan

    Tuesday, 22.07.2014 11:34 | answer
  10. [10] Libor

    Dobrý deň,

    spravujem exchange 2010 a v poslednej dobe sa stáva často že sa nevidí edge a exchange. Musím to riešiť zrušením subscription a znovu vytvorením. Existuje nejaký presný postup pre príkazy power shell na rušenie a vytváranie subscription ?

    Už neviem v čom je chyba.

    Ďakujem

    Lib

    Thursday, 28.04.2016 12:25 | answer
Add comment

Insert tag: strong em link

Help:
  • maximum length of comment is 2000 characters
  • HTML tags are not allowed (they will be removed), you can use only the special tags listed above the input field
  • new line (ENTER) ends paragraph and start new one
  • when you respond to a comment, put the original comment number in squar brackets at the beginning of the paragraph (line)