Archive for the ‘Exchange’ Category

I had a need to extract email body from Office 365 mailbox from “non standard” mailbox folder (Not Inbox), so i edited this nice script to satisfy my need:

Download and install Microsoft Exchange Web Services Managed API 2.0

By default it’s installed in

C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll

This script will look for all emails with “Remove” word in subject,stored in “Processed” folder, get email subject and body, then move email to “done” folder.



# Set the path to your copy of EWS Managed API
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
# Load the Assemply

# Create a new Exchange service object
$service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService

#These are your O365 credentials
$Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($mail,$password)

# this TestUrlCallback is purely a security check
$TestUrlCallback = {
param ([string] $url)
if ($url -eq "") {$true} else {$false}
# Autodiscover using the mail address set above

# get a handle to the inbox
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)

$MailboxRootid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root, $email) # selection and creation of new root
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$MailboxRootid)
# switch to "Processed" folder
$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(100) #page size for displayed folders
$fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep; #Search traversal selection Deep = recursively
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::Displayname,$USER_DEFINED_FOLDER_IN_MAILBOX)
$findFolderResults = $MailboxRoot.FindFolders($SfSearchFilter,$fvFolderView)

$Folder = ""

# create Property Set to include body and header of email
$PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)

# set email body to text
$PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text;

# extract email subject and body
foreach ($Fdr in $findFolderResults.Folders)
$theDisplayName = $Fdr.DisplayName
$Folder = $Fdr

# Now to actually try and search through the emails
$textToFindInSubject = "Remove"

$emailsInFolder = $Folder.FindItems(9999) # <-- Successfully finds ALL emails with no filtering, requiring iterative code to find the ones I want.
foreach($individualEmail in $emailsInFolder.Items)
if($individualEmail.Subject -match "$textToFindInSubject")
# found the email
echo "Successfully found the email!"

$searchfilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::Subject,$textToFindInSubject)
$itemView = new-object Microsoft.Exchange.WebServices.Data.ItemView(999)
$searchResults = $service.FindItems($Folder.ID, $searchfilter, $itemView)

# Find destination folder

$TargetFolderSearch = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::Displayname,"done") #for each folder in mailbox define search
$TargetFolder = $MailboxRoot.FindFolders($TargetFolderSearch,$fvFolderView) 

foreach($result in $searchResults)
# load the additional properties for the item
$subj = $result.Subject

echo "Subject"$subj
echo "Body: $($result.Body.Text)"

# move email to "done" folder





In my previous article we performed database backup using Windows Backup,and in this one we’ll restore database to folder c:\b



Available backups are shown:

Because i backed up folders,not entire drive,i chose Files and folders

I selected mailboxdatabase folder



Click recover


Database and transaction log files are restored to same folder (c:\b)

Restoring to recovery database

A recovery database is a special  mailbox database that allows mounting and extracting data from a restored mailbox database.

Database we just has restored is in dirty shutdown state (there are transactions that are await to be committed to the database).

We’ll use eseutil utility which is part of Exchange to bring database to clear shutdown mode (database is correctly detached-so we can mount this database file to recovery database)

PS C:\b> eseutil /mh '.\bigfirm_db01,on_bigfirm.edb'

/m displays headers of database files and transaction log files

/h – dump database header


To get Clean Shutdown,we must perform soft database recovery (transaction logs are replayed into an offline file backup copy of a database)

PS C:\b> eseutil /R E00 /l .\ /d .\

/R replays transaction log files or rolls them forward to restore a database to internal consistency or to bring an older copy of a database up to date-

/l path to log files

/d path to database file

Both log and database files are in same folder-c:\b,(I cd into that folder,that’s why  .\ is used -current folder)

E00 logfile prefix (note that all log files start with E0)



Check database status,it should be in clean shutdown mode now

Now we can mount edb file to recovery database

Creating recovery database

Recovery database is created as any other mailbox database except we need to specify -recovery switch,

edb path is fedb file to database we recovered using Windows Backup and log files are in c:\b folder (also restored from backup)

[PS] C:\Windows\system32>New-MailboxDatabase -Server dc -Name recoverydatabase -Recovery -EdbFilePath 'C:\b\bigfirm_db01,on_bigfirm.edb' -LogFolderPath 'c:\b'
[PS] C:\Windows\system32>Mount-Database recoverydatabase


Performing restore from recovery database

In this example we will recover emails from deleteditems folder from recovery database

[PS] C:\Windows\system32>New-MailboxRestoreRequest -SourceDatabase recoverydatabase -SourceStoreMailbox "don hall" -TargetMailbox "don hall" -IncludeFolders delete items

Exchange Server 2013 backup

Posted: September 8, 2015 in Exchange

In this post we will backup Exchange Server using Windows backup as well as PowerShell and Batch script

-Backup should be created on remote share

-Full backup should be performed

-The backup should be performed locally on the server

-If we chose full VSS backup,log truncation will occur

Checking if Windows backup is installed:

PS C:\Users\Administrator>Get-WindowsFeature -Name *backup*

Display Name Name Install State
------------ ---- -------------
[ ] Windows Server Backup Windows-Server-Backup Available

Install it:

PS C:\Users\Administrator>Install-WindowsFeature windows-server-backup

Run GUI (windows server backup)


We can perform one time or scheduled backup,in this example i used scheduled backup:


Select Custom (we will backup only Exchange server data)



I chose to backup logging and database folders



If you want to truncate log files choose Advanced settings and click VSS full backup,othervise,leave VSS copy backup


Set the time at which you want the backup to be performed



Set backup destination




Because we selected VSS full backup,log files are erased


Check backup status:

[PS] C:\Windows\system32>Get-MailboxDatabase -Status | select name,LastFullBackup

Name LastFullBackup
---- --------------
bigfirm_db01,on:bigfirm 07.09.2015. 21:57:56

PowerShell alternative:

Instead of GUI,we can use wbadmin utility,create a scheduled task and run it in predefined time

PS C:\Users\Administrator> wbadmin start backup -backuptarget:\\\backup -user:gordon -password:1234 "-include:C:\Program Files\Microsoft\Exchange Server\V15\Logging,C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\bigfirm_db01*" -vssfull -quiet > C:\Backup.txt

Backup.txt will be created at the end of backup procedure


CMD Batch:

C:\Users\Administrator> wbadmin start backup -backuptarget:\\\backup -user:gordon -password:1234 -include:"C:\Program Files\Microsoft\Exchange Server\V15\Logging,C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\bigfirm_db01*" -vssfull -quiet > C:\Backup.txt

Message Classifications allow users to assign a tag to a message, such as marking it confidential.These informations Exchange Server and Outlook treat in a special fashion.When a message is classified, the message contains specific metadata that describes the intended use or audience of the message.

Classifications can be created only through EMS:

[PS] C:\Windows\system32>New-MessageClassification -Name "my classification" -DisplayName "MC" -RecipientDescription "This message may containt confidental information" -SenderDescription "Handle with care"

-RecipientDescription specifies text visible on recipient side

-SenderDescription text visible on sender side

After creating,Classifications need to be exported to xml file.Scripts folder in Exchange install directory contains script Export-OutlookClassification.ps1 which exports classifications

[PS] C:\>cd "C:\Program Files\Microsoft\Exchange Server\V15\Scripts"
[PS] C:\>C:\Program Files\Microsoft\Exchange Server\V15\Scripts>.\Export-OutlookClassification.ps1 > C:\1.xml

Classifications needs to be imported to outlook on every workstations through registry keys.

I am suprised Microsoft didn’t find more elegant way for importing classifications.

[HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Common\Policy]  office 2007
[HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Common\Policy]  office 2010
[HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common\Policy] office 2013

AdminClassificationPath Specifies the full path and filename of the exported XML

EnableClassifications  enables (1) or disables (0) classifications

TrustClassifications  Outlook trusts classifications on messages that are sent to users on legacy Exchange Server Mailbox servers (1) or not (0)

In case you must deploy classifications on many computers (outlook 2013),i created a little batch script which can be deployed via GPO or PSExec tool

REG ADD HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\15.0\Common\Policy /f /v AdminClassificationPath /t REG_SZ /d c:\\1.xml
REG ADD HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\15.0\Common\Policy /f /v EnableClassifications /t REG_DWORD /d 00000001
REG ADD HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\15.0\Common\Policy /f /v TrustClassifications /t REG_DWORD /d 00000001

Restart outlook,compose new message-options-permission (click little “triangle” and choose classification


Sender’s perspective


Receiver’s side:


The Data Loss Prevention Policy allows users to define policies and policy rules for the organization to improve protection of information usually sent through email, including financial and personal data.DLP policies contain sets of conditions, which are made up of transport rules, actions, and exceptions.

In this example we’ll create policy which,in case someone in organization,send a mail with word “salary” in subject or body,report will be sent to administrator.

From ECP click compliance management,data loss prevention,’triangle” near + and choose New custom DLP policy:


Select policy and edit it (pencil icon)


Click rules,select “triangle” again 🙂 and select Notify sender when sensitive information is sent outside the organization


Select “the sender is this person” (track messages sent by specific people-don hall)


Select desired user,click add and click OK again


We now need to add second condition-track specific word in subject or body (salary)



What to do when condition is met-add action (notify adminstrator)


On first “select one” choose administrator



and the second select one choose “Include original mail”



When we click save,transport rule is automatically created (mail flow-rules)


Testing and verifification:

From don.hall  i sent email to my hotmail account with subject salary and administrator got this email


Retention Policies in Exchange 2013

Posted: September 2, 2015 in Exchange

Retention policies are applied to mailboxes to apply message retention settings. A mailbox can’t have more than one retention policy.It’s a collection of retention tags that can be applied to a mailbox.

Personal tags can apply to folders users create themselves or to individual items.It’s premium Exchange feature and requires an Exchange Enterprise client access license (CAL).

A retention policy tag (RPT) applies retention settings to the default folders (Inbox, Deleted Items, and Sent Items) in a mailbox, and all items that are in these default folders inherit the folders’ policy tag.

More about tags:

To create policy,retention policy tag must be created first (action we want po pertorm)

In this example i’ll create 2 retention policy tags,one will archive messages after 30 days and another will permanently delete messages after 5 days:

[PS] C:\Windows\system32>New-RetentionPolicyTag "delete after 5 days" -Type deleteditems -RetentionEnabled $true -AgeLimitForRetention 5 -RetentionAction permanentlydelete
[PS] C:\Windows\system32>New-RetentionPolicyTag "archive" -RetentionEnabled $true -AgeLimitForRetention 30 -RetentionAction movetoarchive -Type personal

-Type deleteditems applies tag to deleted itelms folder

-Type personal applies tag to custom user folder (user can apply this tag to any custom created folder)

-retentionenabled $true activates/enables tag

-agelimitforretention retention period (in days)

Tags can be created from GUI too,using Exhange control panel:

compliance management-retention tags-“+” sign:


We can add these policy tags to default retention policy (Default MRM Policy) or create a new one.

I created new (delete & archive) and addedd two policy tags:

[PS] C:\Windows\system32>New-RetentionPolicy "delete & archive" -RetentionPolicyTagLinks "delete after 5 days","archive"

Using ECP

compliance management-retention policies-“+” sign,add previouslu created tags:


Check if we did it right:

[PS] C:\Windows\system32>(Get-RetentionPolicy "delete & archive").RetentionPolicyTagLinks | Format-Table name


We can assign policy to individual mailbox(es)

[PS] C:\Windows\system32>Set-Mailbox "don hall" -RetentionPolicy "delete & archive"

or to all mailboxes:

[PS] C:\Windows\system32>Get-mailbox | Set-Mailbox -RetentionPolicy "deleted items"

To apply policy immediately,we need to start ManagedFolderAssistant (It processes retention policies for managed folders and applies retention policy tags to items in mailboxes)

Start assistant for specific mailbox:

[PS] C:\Windows\system32>Start-ManagedFolderAssistant -Identity "don hall"

or to all mailboxes

[PS] C:\Windows\system32>get-mailbox | Start-ManagedFolderAssistant


From Outlook Web Access,select folder and assign policy tag (for deleted items it’s set by default)


Or in outlook,right click folder-properties,policy to see which policy tags are applied


Role Based Access Control (RBAC) was first introduced in Exchange 2010 as a way to give an excange administrator granular control over Exchange Server,in other words what privileges administrator has.RBAC consists of four “modules” which,combined together form a permission model that forms level of access to Exchage features:

Management Role scope “Where” does something applies (OU,user,group)

Management role “What” actions (cmdlets-expressed via Management Role Entries) we want to apply to user

Management role group “Who” can execute cmdlets (Powershell commands) specified in Management Role entries

Management role assignment binds users to actions that we want to assign to them

In this example i’ll remove administrator right to create new mailbox database

First,we need to identify existing managementrole  contains new-mailboxdatabase cmdlets

[PS] C:\Users\administrator.JA\Desktop>get-managementrole "databases" | fl description


To make sure,review powershell commands covered by “database” managementrole:

[PS] C:\Users\administrator.JA\Desktop>get-managementroleentry "databases\*" | fl


In case you wonder why i didn’t use “databases*” instead “databases\*”:


We will use “databases” roleentry as a base for our own,named “prohibit database creation” management entry (“What” cmdlets are allowed to run):

[PS] C:\Users\administrator.JA\Desktop>New-ManagementRole "prohibit database creation" -Parent "databases"

To make sure it contains needed powershell commands:


Because we want to remove new-mailboxdatabase cmdlet,we need to remove it from our newly created entry

[PS] C:\Users\administrator.JA\Desktop>remove-ManagementRoleEntry "prohibit database creation\new-mailboxdatabase" -Confirm:$false

Check again to see that new-mailboxdatabase was removed from “prohibit database creation” managemententry:

[PS] C:\Users\administrator.JA\Desktop>Get-ManagementRoleEntry "prohibit database creation\*" | ft


I created OU for admins who will have cmdlets assigned from “prohibit database creation” entry,and created administrator named test and put him to OU

C:\Documents and Settings\Administrator>dsadd ou ou="fake exchange admins",dc=ja,dc=com

We need now to create role group (“Who“) can perform cmdlets specified in “prohibit database creation” managemententry,

and where (OU “fake exchange admins”)

[PS] C:\Users\administrator.JA\Desktop>new-rolegroup "no database creation allowed" -Roles "prohibit database creation" -RecipientOrganizationalUnitScope " exchange admins"
[PS] C:\Users\administrator.JA\Desktop>add-rolegroupmember "no database creation allowed" -member test

New rolegroup “no database creation allowed” was created and assigned our managementroleentry,and rolegroup is bound to OU “fake exchange admins”

Rolegroup can be created using ECP:

Permissions-Admin roles,”+” sign:



Now i logged admin test and tried to run new-mailboxdatabase cmdlet: