Sunday, September 19, 2010

Recipient \ Email Address Policy GUI and browser for Exchange 2007 / 2010

Recipient policies where first introduced in Exchange 2003 and later became email address policies in Exchange 2007 where we where all introduced to the joys and sorrows of Opath. While policies are a simple idea and a good method to do this type of thing the complexities of what happens underneath can be hard to get your head around and test and this can at times lead to the odd mistake. While there is a preview box when your modifying an Address list policy if you wanted to look at the bigger picture of the filter that the address policy represents as it is and could be applied to active directory objects, this is where it can be useful to use a script. The other thing to take into account when looking a policies is the objects where the application of the address policies have been disabled. So what I've done is build a GUI to help this the first thing this script does is enumerate all the policy objects and retrieve the following properties that are associated with these object.

GatewayProxy - This contains the proxyaddresses that will be applied by the policy

msExchQueryFilter - This is the Opath filter for the policy

msExchPolicyOrder - This is the priority of the address policy

msExchPurportedSearchUI - This is a little bit of cheat as this property is used for the UI but it does contain a LDAP filter that can be used directly in ADSI so this is the property that I've used to search active directory for objects that the policy relates to.

GUID this is stored so it can be compared to the the msexchPoliciesIncluded property to work out if a policy has been applied to a specific object.

To work out if a policy has been applied to an object and also work out if policies have been disabled two properties are important. If polices have been disabled via the "Automatically update e-mail addresses based on e-mail address policy" then the msExchPoliciesExcluded will be set to 26491CFC-9E50-4857-861B-0CB8DF22B5D7.

Once a policy has been applied to an AD object the msexchpoliciesincluded will be updated with the GUID of the policy that has been applied. So when it comes time to enumerating applied polices using a script these a properties that you can put to use.

What happens when you hit the search button is the script does a ADSI query of active directory based on the LDAP filter and will return the objects that match this filter and tell you want policis has been applied to these objects. The radio button let you filter on all object, just the ones where the policy has been applied or disabled.

Some other things this script can be used for are backing up the current proxyaddress setting of accounts before you make any changes.

I've put a download of this script here the script itself looks like

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$form = new-object System.Windows.Forms.form
$raCollection = @()
$usrCollection = @()
$policyhash = @{ }
# $policyhash.Add("26491CFC-9E50-4857-861B-0CB8DF22B5D7","Disabled")

function UpdateListBoxPolicy(){
foreach ($prxobj in $raCollection){
if ($prxobj.PolicyName -eq $policyNameDrop.SelectedItem.ToString()){
$lbListView.clear()
$lbListView.Columns.Add("Property",80)
$lbListView.Columns.Add("Value",220)
$item1 = new-object System.Windows.Forms.ListViewItem("GUID")
$item1.SubItems.Add($prxobj.GUID.ToString())
$lbListView.items.add($item1)
$item1 = new-object System.Windows.Forms.ListViewItem("OpathFilter")
$item1.SubItems.Add($prxobj.OpathFilter.ToString())
$lbListView.items.add($item1)
$item1 = new-object System.Windows.Forms.ListViewItem("gatewayProxy")
if ($prxobj.gatewayProxy -is [system.array]){
$item1.SubItems.Add(([string]::join(";", $prxobj.gatewayProxy)))
}
else{
$item1.SubItems.Add($prxobj.gatewayProxy.ToString())
}
$lbListView.items.add($item1)
$item1 = new-object System.Windows.Forms.ListViewItem("LDAPFilter")
$item1.SubItems.Add($prxobj.LDAPFilter.ToString())
$lbListView.items.add($item1)
$item1 = new-object System.Windows.Forms.ListViewItem("msExchPolicyOrder")
$item1.SubItems.Add($prxobj.msExchPolicyOrder.ToString())
$lbListView.items.add($item1)
}
}
}

function ExportGrid(){
$exFileName = new-object System.Windows.Forms.saveFileDialog
$exFileName.DefaultExt = "csv"
$exFileName.Filter = "csv files (*.csv)|*.csv"
$exFileName.InitialDirectory = "c:\temp"
$exFileName.ShowHelp = $true
$exFileName.ShowDialog()
if ($exFileName.FileName -ne ""){
$logfile = new-object IO.StreamWriter($exFileName.FileName,$true)
$logfile.WriteLine("DisplayName,PrimaryEmailAdrress,ProxyAddresses,RecipientPolicy")
foreach($row in $msTable.Rows){
$logfile.WriteLine("`"" + $row[0].ToString() + "`"," + $row[1].ToString() + "," + $row[2].ToString() + "," + $row[3].ToString())
}
$logfile.Close()
}



}

function SearchforObjects(){
$policyobject = ""
foreach ($prxobj in $raCollection){
if ($prxobj.PolicyName -eq $policyNameDrop.SelectedItem.ToString()){
$policyobject = $prxobj.LDAPFilter.ToString()
}
}
$msTable.clear()
$dfDefaultRootPath = "LDAP://" + $root.DefaultNamingContext.tostring()
$dfRoot = [ADSI]$dfDefaultRootPath
$gfGALQueryFilter = $policyobject
$dfsearcher = new-object System.DirectoryServices.DirectorySearcher($dfRoot)
$dfsearcher.Filter = $gfGALQueryFilter
$dfsearcher.PageSize = 1000
$dfsearcher.PropertiesToLoad.Add("msexchPoliciesIncluded")
$dfsearcher.PropertiesToLoad.Add("proxyAddresses")
$dfsearcher.PropertiesToLoad.Add("mail")
$dfsearcher.PropertiesToLoad.Add("displayName")
$dfsearcher.PropertiesToLoad.Add("distinguishedName")
$dfsearcher.PropertiesToLoad.Add("msExchPoliciesExcluded")
$srSearchResult = $dfsearcher.FindAll()
foreach ($emResult in $srSearchResult) {
$emProps = $emResult.Properties
$DisplayName = ""
$PrimaryEmailAdrress = ""
$ProxyAddresses = ""
$RecipientPolicy = ""
if($emProps.msexchpoliciesincluded -ne $null){
$polarray = $emProps.msexchpoliciesincluded[0].Split(",")
foreach($pol in $polarray){
$pol = $pol.ToString().Replace("{","").Replace("}","")
if ($policyhash.ContainsKey($pol.ToString())){
$RecipientPolicy = $policyhash[$pol.ToString()]

}
}
}
if ($emProps.msexchpoliciesexcluded -ne $null){
foreach($pol in $emProps.msexchpoliciesexcluded){
$pol = $pol.ToString().Replace("{","").Replace("}","")
$pol.ToString()
if ($pol.ToString() -eq "26491CFC-9E50-4857-861B-0CB8DF22B5D7"){
$RecipientPolicy = "Disabled"

}
}
}
$DisplayName = $emResult.Properties["displayname"][0]
$PrimaryEmailAdrress = $emResult.Properties["mail"][0]
$ProxyAddresses = [string]::join(";",$emProps.proxyaddresses)
if($rbinc.Checked -eq $true){
$msTable.rows.add($DisplayName,$PrimaryEmailAdrress,$ProxyAddresses,$RecipientPolicy)
}
if($rbinc1.Checked -eq $true -band $RecipientPolicy -eq $policyNameDrop.SelectedItem.ToString()){
$msTable.rows.add($DisplayName,$PrimaryEmailAdrress,$ProxyAddresses,$RecipientPolicy)
}
if($rbinc2.Checked -eq $true -band $RecipientPolicy -eq "Disabled"){
$msTable.rows.add($DisplayName,$PrimaryEmailAdrress,$ProxyAddresses,$RecipientPolicy)
}

}
$dgDataGrid.Datasource = $msTable
}

$root = [ADSI]'LDAP://RootDSE'
$cfConfigRootpath = "LDAP://" + $root.ConfigurationNamingContext.tostring()
$configRoot = [ADSI]$cfConfigRootpath
$searcher = new-object System.DirectoryServices.DirectorySearcher($configRoot)
$searcher.Filter = "(objectClass=msexchRecipientPolicy)"
$searchresults = $searcher.FindAll()
foreach ($searchresult in $searchresults){
$plcobj = "" | select PolicyName,GUID,gatewayProxy,OpathFilter,LDAPFilter,msExchPolicyOrder
$Policyobject = New-Object System.DirectoryServices.directoryentry
$Policyobject = $searchresult.GetDirectoryEntry()
$plcobj.PolicyName = $Policyobject.Name.Value
$plcobj.GUID = [GUID]$Policyobject.ObjectGUID.Value
$plcobj.OpathFilter = $Policyobject.msExchQueryFilter.Value
$plcobj.gatewayProxy = $Policyobject.GatewayProxy.Value
$plcobj.msExchPolicyOrder = $Policyobject.msExchPolicyOrder.Value
foreach ($val in $Policyobject.msExchPurportedSearchUI){
if($val -match "Microsoft.PropertyWell_QueryString="){
$plcobj.LDAPFilter = $val.substring(35,($val.length-35))
}
}
$raCollection += $plcobj
$policyhash.add($plcobj.GUID.ToString(),$plcobj.PolicyName)
}


$msTable = New-Object System.Data.DataTable
$msTable.TableName = "ProxyAddress"
$msTable.Columns.Add("DisplayName")
$msTable.Columns.Add("PrimaryEmailAdrress")
$msTable.Columns.Add("ProxyAddresses")
$msTable.Columns.Add("RecipientPolicy")


$PolicylableBox = new-object System.Windows.Forms.Label
$PolicylableBox.Location = new-object System.Drawing.Size(10,20)
$PolicylableBox.size = new-object System.Drawing.Size(120,20)
$PolicylableBox.Text = "Select Policy Name : "
$form.controls.Add($PolicylableBox)

# Add Policy Drop Down
$policyNameDrop = new-object System.Windows.Forms.ComboBox
$policyNameDrop.Location = new-object System.Drawing.Size(130,20)
$policyNameDrop.Size = new-object System.Drawing.Size(200,30)
$policyNameDrop.Enabled = $true
foreach ($prxobj in $raCollection){
$policyNameDrop.Items.Add($prxobj.PolicyName)
}
$policyNameDrop.Add_SelectedValueChanged({UpdateListBoxPolicy})
$form.Controls.Add($policyNameDrop)

$policySettingslableBox = new-object System.Windows.Forms.Label
$policySettingslableBox.Location = new-object System.Drawing.Size(340,20)
$policySettingslableBox.size = new-object System.Drawing.Size(80,20)
$policySettingslableBox.Text = "Policy Settings"
$form.controls.Add($policySettingslableBox)

$lbListView = new-object System.Windows.Forms.ListView
$lbListView.Location = new-object System.Drawing.Size(450,20)
$lbListView.size = new-object System.Drawing.Size(350,100)
$lbListView.LabelEdit = $True
$lbListView.AllowColumnReorder = $True
$lbListView.CheckBoxes = $False
$lbListView.FullRowSelect = $True
$lbListView.GridLines = $True
$lbListView.View = "Details"
$lbListView.Sorting = "Ascending"
$form.controls.Add($lbListView)

# Add RadioButtons
$rbinc = new-object System.Windows.Forms.RadioButton
$rbinc.Location = new-object System.Drawing.Size(150,50)
$rbinc.size = new-object System.Drawing.Size(220,17)
$rbinc.Checked = $true
$rbinc.Text = "All objects Policy Query matches"
$form.Controls.Add($rbinc)

$rbinc1 = new-object System.Windows.Forms.RadioButton
$rbinc1.Location = new-object System.Drawing.Size(150,70)
$rbinc1.size = new-object System.Drawing.Size(220,17)
$rbinc1.Checked = $false
$rbinc1.Text = "Only objects with Apply policy enabled"
$form.Controls.Add($rbinc1)

$rbinc2 = new-object System.Windows.Forms.RadioButton
$rbinc2.Location = new-object System.Drawing.Size(150,90)
$rbinc2.size = new-object System.Drawing.Size(220,17)
$rbinc2.Checked = $false
$rbinc2.Text = "Only objects with Apply policy disabled"
$form.Controls.Add($rbinc2)



$exButton1 = new-object System.Windows.Forms.Button
$exButton1.Location = new-object System.Drawing.Size(10,70)
$exButton1.Size = new-object System.Drawing.Size(125,20)
$exButton1.Text = "Search"
$exButton1.Add_Click({SearchforObjects})
$form.Controls.Add($exButton1)

# Add Export Grid Button

$exButton2 = new-object System.Windows.Forms.Button
$exButton2.Location = new-object System.Drawing.Size(10,760)
$exButton2.Size = new-object System.Drawing.Size(125,20)
$exButton2.Text = "Export Grid"
$exButton2.Add_Click({ExportGrid})
$form.Controls.Add($exButton2)



# Add DataGrid View

$dgDataGrid = new-object System.windows.forms.DataGridView
$dgDataGrid.Location = new-object System.Drawing.Size(10,145)
$dgDataGrid.size = new-object System.Drawing.Size(1000,600)
$dgDataGrid.AutoSizeRowsMode = "AllHeaders"
$form.Controls.Add($dgDataGrid)

$form.Text = "Address Policy GUI"
$form.size = new-object System.Drawing.Size(1200,750)
$form.autoscroll = $true
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()

Friday, September 10, 2010

Cleaning up and Reporting on Items based on the Subject on Exchange using a EWS search with Powershell

If your unaware there is nasty mass mailer virus outbreak at the moment if you haven't already i would strongly urge you to visit and implement the measures in http://social.technet.microsoft.com/wiki/contents/articles/worm-win32-visal-b.aspx

The above gives the best and quickest method for cleaning the affects of an outbreak using the EMS export-mailbox cmdlet but i thought I'd give some alternate methods using EWS . I can't guarantee any of these methods like i would with Export-mailbox and I would expect them to be slower (and possibly very slow) but they may come in use especially if your access is limited but you can use EWS Impersonation or if you looking to do some reporting based on subject.

Finding Items based on there Subject is relatively simple in EWS and involves the use of a Search filter or if your lucky enough to be using Exchange 2010 you can make use of AQS which I blogged about earlier here . With a virus outbreak they generally start on a particular date so it makes sense to make your query more efficient by only searching for items that where received in the last 7 days. So a search filter for 2007 would look like

$Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::Subject, $subjecttoSearch)
$Sflt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, $MailDate)
$sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
$sfCollection.add($Sfir)


The AQS query for the same thing would look like AQSQuery = "Received:this week AND subject:`"" + $subjecttoSearch + "`"" . There is one very important catch with the AQS query is that it will do a exact phrase match but not a exact subject match. So for example if you where trying to match the phrase "here you have" in the subject it would also match "here you have a example of" there are different operators that you can use in AQS but not one that i could find that would do a exact property match(I anybody finds an AQS query that works (emphasis on works rather then should work based on the documentation) please let me know). To get around this and also as a double check before you delete anything a simple logic if statement can be used in your code.

When it comes to deleting Items in the EWS Managed API you can use the Delete method of the Item object which would basically call a deleteItem operation each time you called this method or a faster method is create an array of itemid's that you would like deleted and then use the batch deleteItems method which is the method I've used.

The scripts are setup to use Delegation but if you want to use impersonation instead just add the following line

$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)

Because searching like this is not only usefully for deleting Items but for also reporting on things I've created a reporting version of the scripts as well that just emails a html report of a what it finds within a mailbox and includes the transport headers of the messages in question. The script I've created does a deep traversal to get the folderid details and then a single finditems on each folder the 2007 version using searchfilters and the 2010 version use AQS.

The delete scripts do a SoftDelete meaning the item goes into the dumpster of the folder it was deleted from (you could make this a hard delete).

Before using these script you need to customize the following variable with the subject you want to search for the example I've used is I hate spam

$subjecttoSearch = "I hate Spam"

You also need to set the mailbox name to run against or change it to $arg[0] and run the script with a cmdline argument. In the reporting script the To,From and SMTP server needs to be set.

I've put a download of all 4 scripts here the 2007 delete version looks like.

$MailboxName = "user@mailbox.com"

$subjecttoSearch = "I hate Spam"
$MailDate = [system.DateTime]::Now.AddDays(-7)

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)

$deleteMode = [Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete
$aptcancelMode = [Microsoft.Exchange.WebServices.Data.SendCancellationsMode]::SendToNone
$taskmode = [Microsoft.Exchange.WebServices.Data.AffectedTaskOccurrence]::AllOccurrences

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())

$rfRootFolderID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)
$rfRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$rfRootFolderID)
$fvFolderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000);
$fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep
$fvFolderView.PropertySet = $Propset
$ffResponse = $rfRootFolder.FindFolders($fvFolderView);

foreach ($ffFolder in $ffResponse.Folders){
"Checking " + $ffFolder.DisplayName
$Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::Subject, $subjecttoSearch)
$Sflt = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, $MailDate)
$sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And);
$sfCollection.add($Sfir)
$sfCollection.add($Sflt)
$ivview = new-object Microsoft.Exchange.WebServices.Data.ItemView(20000)
$frFolderResult = $ffFolder.FindItems($sfCollection,$ivview)
$Itembatch = [activator]::createinstance(([type]'System.Collections.Generic.List`1').makegenerictype([Microsoft.Exchange.WebServices.Data.ItemId]))
foreach ($miMailItems in $frFolderResult.Items){
if ($miMailItems.Subject -eq $subjecttoSearch){
"****** Found" + $miMailItems.Subject
$Itembatch.add($miMailItems.Id)
}
}
"Number of Items found in folder : " + $Itembatch.Count
if($Itembatch.Count -ne 0){
"Deleting " + $Itembatch.Count + " Items"
$DelResponse = $service.DeleteItems($Itembatch,$deleteMode,$aptcancelMode,$taskmode)
foreach ($dr in $DelResponse) {
$dr.Result
}
}

}







Thursday, September 09, 2010

Getting the Folder Size of a folder using EWS

One of the things missing from the standard folder properties when you use EWS to access a mailbox or public folder is the size of the folder. Those that have used other API's to do mailbox and public folder size reporting should already know about the extended mapi property PR_Extended_Message_Size this is what you also need to use in EWS to get the folder size to define this in C# you can use

ExtendedPropertyDefinition PR_Extended_Message_Size = new ExtendedPropertyDefinition(3592, MapiPropertyType.Long);
PropertySet psPropertySet = new PropertySet(BasePropertySet.FirstClassProperties) { PR_Extended_Message_Size };
Folder Inbox = Folder.Bind(service, WellKnownFolderName.Inbox, psPropertySet);
Object FolderSize = null;
if (Inbox.TryGetProperty(PR_Extended_Message_Size, out FolderSize)) {
Console.WriteLine(FolderSize);
}


You can also make use of this in a script if you want an alternative to Get-MailboxFolderStatistics eg if you wanted to show the size of ever folder in a mailbox you can use the following script I've put a download of this here

$MailboxName = "user@domain.com"

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())

$rfRootFolderID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)
$rfRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$rfRootFolderID)
$fvFolderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000);
$PR_MESSAGE_SIZE_EXTENDED = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3592, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)
$Propset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$Propset.add($PR_MESSAGE_SIZE_EXTENDED)
$fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep
$fvFolderView.PropertySet = $Propset
$ffResponse = $rfRootFolder.FindFolders($fvFolderView);

foreach ($ffFolder in $ffResponse.Folders){
$fldObject = "" | select FolderName,FolderSize
$folderSize = $null
$ptProptest2 = $ffFolder.TryGetProperty($PR_MESSAGE_SIZE_EXTENDED, [ref]$folderSize)
$fldObject.FolderName = $ffFolder.DisplayName
$fldObject.FolderSize = [INT]$folderSize
$ReportingCollection += $fldObject
}
$ReportingCollection