Posts Tagged ‘EWS’

Per my backup script before , this restores

You will need to go through and change the values in %

 

$mailbox = Get-Mailbox %mailbox%
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$s.AutodiscoverUrl($mailAddress);
 
 
$cred = New-Object System.Net.NetworkCredential("%username%","%password%")
 
 
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$s.Credentials = $cred
 
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
 
$file = [System.IO.File]::ReadAllBytes("c:\%folder%\%binaryfile%")
$data = [System.Convert]::ToBase64String($file)
 
#change folder where needed
$folderobject = GetFolder($MailboxRoot, "\Quick Step Settings\");
$folderid = $folderobject.id.uniqueid
$folderchangekey = $folderobject.id.ChangeKey
 
$expRequest = @"
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
      xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2010_SP1" />
  </soap:Header>
  <soap:Body>
  <m:UploadItems>
      <m:Items>
        <t:Item CreateAction="CreateNew" IsAssociated="true">
          <t:ParentFolderId  Id="$folderid" ChangeKey="$folderchangekey"/>
          <t:Data>$data</t:Data>
        </t:Item>
      </m:Items>
    </m:UploadItems>
  </soap:Body>
</soap:Envelope>
"@
 
$mbMailboxFolderURI = New-Object System.Uri($s.url)
$wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)
$wrWebRequest.KeepAlive = $false;
$wrWebRequest.Headers.Set("Pragma", "no-cache");
$wrWebRequest.Headers.Set("Translate", "f");
$wrWebRequest.Headers.Set("Depth", "0");
$wrWebRequest.ContentType = "text/xml";
$wrWebRequest.ContentLength = $expRequest.Length;
$wrWebRequest.Timeout = 60000;
$wrWebRequest.Method = "POST";
$wrWebRequest.Credentials = $cred
$bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($expRequest);
$wrWebRequest.ContentLength = $bqByteQuery.Length;
$rsRequestStream = $wrWebRequest.GetRequestStream();
$rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Length);
$rsRequestStream.Close();
$wrWebResponse = $wrWebRequest.GetResponse();
$rsResponseStream = $wrWebResponse.GetResponseStream()
$sr = new-object System.IO.StreamReader($rsResponseStream);
$rdResponseDocument = New-Object System.Xml.XmlDocument
$rdResponseDocument.LoadXml($sr.ReadToEnd());
$Datanodes = @($rdResponseDocument.getElementsByTagName("m:ResponseCode"))
$Datanodes
VN:F [1.9.22_1171]
Rating: 1.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: -1 (from 1 vote)

Wow , possible my biggest EWS Powershell script, Big thanks go to Glen for the missing piece of the jigsaw. The project started as a way to copy Quick Copy settings between users when needed.

Outlook doesn’t provide much functionality to do this itself, you can use the famous redemtion.dll for this task  http://www.dimastr.com/redemption/rdoquicksteps.htm , but I’m more of a server side guy than a client side, Our Outlook Enviroment has too many macros already!

I knew how to get more Inbox items , but have never dived into the “Associated Contents Table”. Using the free MFCMAPI.exe tool , I explored the mailbox to find the folder I need as well as the table and after hours or tinkering and borrowing code we are good!

You will need to go through and change the values in %

This is the download script , I will paste the SOAP upload script in another post

$mailbox = Get-Mailbox %mailbox%
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$s.AutodiscoverUrl($mailAddress);
 
#needed for XML Soap
$cred = New-Object System.Net.NetworkCredential("%username%","%password%")
 
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind
$s.Credentials = $cred
 
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
#choose the folder name you want to download the Configuration items from
$folderobject = GetFolder($MailboxRoot, "\Quick Step Settings\");
$sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Microsoft.CustomAction")
$Itemview = new-object Microsoft.Exchange.WebServices.Data.ItemView(20)
$ItemView.PropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$ItemView.Traversal = [Microsoft.Exchange.Webservices.Data.ItemTraversal]::Associated
#$folderid = new-object  Microsoft.Exchange.WebServices.Data.Folderid([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$mailAddress)
$folderid = $folderobject.Id
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$folderid)
$pspropset = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
$mails  = $inboxFolder.finditems($sfSearchFilter,$Itemview)
 
#loop to go through all the items in the folder
$count=0
foreach($Item in $mails.Items)
{ 
 
#gets the id for the SOAP XML Request
$itemid = $mails.Items[$count].Id.Uniqueid
 
$expRequest = @"
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
      xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2010_SP1" />
  </soap:Header>
  <soap:Body>
    <m:ExportItems>
      <m:ItemIds>
        <t:ItemId Id="$itemid"/>
      </m:ItemIds>
    </m:ExportItems>
  </soap:Body>
</soap:Envelope>
"@
$mbMailboxFolderURI = New-Object System.Uri($s.url)
$wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)
$wrWebRequest.KeepAlive = $false;
$wrWebRequest.Headers.Set("Pragma", "no-cache");
$wrWebRequest.Headers.Set("Translate", "f");
$wrWebRequest.Headers.Set("Depth", "0");
$wrWebRequest.ContentType = "text/xml";
$wrWebRequest.ContentLength = $expRequest.Length;
$wrWebRequest.Timeout = 60000;
$wrWebRequest.Method = "POST";
$wrWebRequest.Credentials = $cred
$bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($expRequest);
$wrWebRequest.ContentLength = $bqByteQuery.Length;
$rsRequestStream = $wrWebRequest.GetRequestStream();
$rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Length);
$rsRequestStream.Close();
$wrWebResponse = $wrWebRequest.GetResponse();
$rsResponseStream = $wrWebResponse.GetResponseStream()
$sr = new-object System.IO.StreamReader($rsResponseStream);
$rdResponseDocument = New-Object System.Xml.XmlDocument
$rdResponseDocument.LoadXml($sr.ReadToEnd());
$Datanodes = @($rdResponseDocument.getElementsByTagName("m:Data"))
$Datanodes
if ($Datanodes.length -ne 0){
	$Data = [System.Convert]::FromBase64String($Datanodes[0].'#text')
#file location
	$fsFileStream = new-object system.io.filestream C:\%folder%\quickcopy$count, ([io.filemode]::create), ([io.fileaccess]::write), ([io.fileshare]::none)
	$fsFileStream.Write($Data, 0, $Data.Length);
    $fsFileStream.Close();
}
$count= $count+1 
 
	}

 

VN:F [1.9.22_1171]
Rating: 1.0/10 (2 votes cast)
VN:F [1.9.22_1171]
Rating: -2 (from 2 votes)
On trying to run a EWS Script the follow error came up

The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

The addition to of the following line above to silenced the problem but did not fix the communication. Instead brought up an new error

“The request failed. The underlying connection was closed: An unexpected error occurred on a send.”

First you can add this line after each of the errors to give you the full error
$error[0] | fl -force

The full error displayed :

System.Management.Automation.PSInvalidOperationException: There is no Runspace available t  scripts in this thread. self sign certificate

The below code needs to be added instead to properly ignore the self signed certificate issues:

## Code From http://poshcode.org/624
## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
 
$TASource[email protected]'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
 
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
 
## end code from http://poshcode.org/624
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: -1 (from 1 vote)
Simple EWS Script to list items in a folder or Subfolder

$mailbox = Get-Mailbox %Usernameofmailboxtocheck%
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
$s.AutodiscoverUrl($mailAddress);
 
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements
 
[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
#Uncomment the two lines below if referencing a folder that is not in the WellKnownFolderNameList ( and Comment Third Line ) 
#$folderobject = GetFolder($MailboxRoot, "\Folder\Path\");
#$folderid = $folderobject.id
$folderid = new-object  Microsoft.Exchange.WebServices.Data.Folderid([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Tasks,$mailAddress)
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$folderid)
 
 
$mails = $inboxFolder.FindItems(20) 
 
    foreach($Item in $mails.Items)
	{ 
 
Write-Host $item.InternetMessageId 
Write-Host $item.Subject
Write-Host $item.DueDate
 
	}
VN:F [1.9.22_1171]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

140257-thumb_exchange_original[1]Transport Limits

Organization Configuration | Hub Transport | Global Settings tab | Transport Settings| properties | General tab.

Send Connector

Organization Configuration> Hub Transport> Send Connectors section. If you double click on each of your connectors (most of you will probably only have one) you will see a “Maximum Message Size” setting.

Receive Connector

Again in the configuration of each of these connectors you set a “Maximum Message Size” like seen below. The setting is changed at Server Configuration> Hub Transport> Receive Connectors.

Mailbox Limits

To set these using the Exchange console: Recipients | Mailbox -> select mailbox (or select another recipient type such as a contact or mail user from the corresponding node) | properties | Mail Flow Settings tab | Message Size Restrictions.

Routing Limits between 2003 and 2010 Environment

Set-RoutingGroupConnector “CONNECTOR NAME” -MaxMessageSize 50Mb

AD Site Links

Set-ADSiteLink “SITE LINK NAME” -MaxMessageSize 50Mb

OWA Attachment Sizes:  (Note: This must be completed on every CAS server)
Use Notepad to change the maxRequestLength value

1. Find the Outlook Web App Web.config file on the Client Access server. The default location is <drive>\Program Files\Microsoft\Exchange Server\V14\ClientAccess\Owa.
2. Make a backup copy of the web.config file.
3. Open the original file using an editor such as Notepad. Don’t use Internet Information Services (IIS) Manager to edit the Web.config file.
4. Find maxRequestLength and change it to the value that you want. The value is stored in kilobytes (KB). The default value is 35000. The following example shows the maxRequestLength value in the Web.config file.
<httpRuntime maxRequestLength=”51200″ />
Note: This is 50 MB (1024 X 50)
5. Save and close the file.

EWS Attachment Sizes:  (Note: This must be completed on every CAS server)
1. Find the EWS Web.config file on the Client Access server. The default location is C:\Program Files\Microsoft\Exchange Server\V14\ClientAccess\exchweb\ews
2. Make a backup copy of the web.config file.
3. Open the original file using an editor such as Notepad. Don’t use Internet Information Services (IIS) Manager to edit the Web.config file.
4. Find maxRequestLength and change it to the value that you want. The value is stored in kilobytes (KB). The default value is 35000. The following example shows the maxRequestLength value in the Web.config file.
<httpRuntime maxRequestLength=”51200″ />
Note: This is 50 MB (1024 X 50)
5. Save and close the file.
Restart IIS.

ActiveSync Attachment Sizes:  (Note: This must be completed on every CAS server)
1. Find the EWS Web.config file on the Client Access server. The default location is C:\Program Files\Microsoft\Exchange Server\V14\ClientAccess\Sync
2. Make a backup copy of the web.config file.
3. Open the original file using an editor such as Notepad. Don’t use Internet Information Services (IIS) Manager to edit the Web.config file.
4. Find maxRequestLength and change it to the value that you want. The value is stored in kilobytes (KB). The default value is 35000. The following example shows the maxRequestLength value in the Web.config file.
<httpRuntime maxRequestLength=”51200″ />
Note: This is 50 MB (1024 X 50)
5. Save and close the file.
Restart IIS.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Below is the command to extract ( Archive ) emails from a particular folder into a PST

#Archive Items from a certain folder
New-MailboxExportRequest -mailbox %mailboxname% -IncludeFolders "path/to/folder/ -ContentFilter {(Received -lt '08/01/2014')} -FilePath \\path\to\pstfile.pst

However due to Exchange updates , the MailboxExport command does not work anymore ( which had the -deletecontent command) and Search-Mailbox does not have any functionality to Include just specific folders. So we have to use powershell EWS below

Note – By default ItemView has a limit of 1000 in exchange, the command below you will probably want to increase this say to 10,000 or even 50,000 so you don’t have to rerun this lots of times. After each run it will tell you how many items it has deleleted. You need to run the powershell script with a useraccount that has a throttling policy set above 1000.

e.g. Set-ThrottlingPolicy PolicyName -EWSFindCountLimit 50000

Set-Mailbox useraccount -ThrottlingPolicy PolicyName

$mailbox = Get-Mailbox %mailboxname%
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010)
$s.AutodiscoverUrl($mailAddress);
 
$ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(10000)
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
 
try {
 
	$FolderObject = GetFolder($MailboxRoot, "path\folder\");
#Date from and To
    $findItemResults = $FolderObject.FindItems("System.Message.DateReceived:01/01/2014..01/08/2014",$ItemView)
 
        foreach ($item in $findItemResults.Items) {
 
                try {
#Comment Below out to not delete
                    [void]$item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
                    $Deleted ++
#Uncomment below to list before deleting
					#Write-host $item.DateTimeReceived 
                } catch {
                    Write-warning "Unable to delete item, $($item.subject).  $($Error[0].Exception.Message)"
                }
            }        
 
 
    if ($Deleted -gt 0) { Write-host "$Deleted mail items deleted from the Inbox." }
} catch {
    Write-warning "Could not connect to Inbox.  $( $_.exception.message )"
}
VN:F [1.9.22_1171]
Rating: 10.0/10 (2 votes cast)
VN:F [1.9.22_1171]
Rating: +3 (from 3 votes)

In Exchange EWS when trying to delete an item you get the following error : cannot find an overload for “delete” and the argument count 0 using

$item.Delete()

 

You need to give it a an enumeration e.g.

They can be found here : http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.deletemode(v=exchg.80).aspx

$item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

I based this script off of one referenced here : http://blogs.msdn.com/b/emeamsgdev/archive/2012/10/29/outlook-code-importing-bank-holidays-from-an-outlook-hol-based-csv-file.aspx?CommentPosted=true#commentmessage

CSV Format

6011-image_thumb_6a014d4e1

However I modified Adding a Category to the item, as well as adding this to All Users of a AD Group recursively instead of a single user. This will add a list of Holidays to Users Calendars across an organisation. If run again it will not import duplicates and have fields there to delete the duplicate Calendar enteries if needed

The user running this will need the impersonation role setup see this :

New users can then have an email sent to them automatically ( http://blogs.technet.com/b/sukum/archive/2013/04/03/send-welcome-email-to-new-mailbox-users.aspx ) with a .HOL file to run ( P.S. The XML did not work in this , I have to add Lines 6-8 from this http://itnuts.wordpress.com/2013/09/03/exchange-2010-automatic-welcome-message-for-a-new-user/)


https://github.com/pariswells/pariswells.com/blob/master/saveappointmentintoalluserscalendar.ps1
VN:F [1.9.22_1171]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

Recently we needed to create an Exchange Web Services Script to Auto Reply from a Mailbox due to Auto Replies being disabled for Spam Reasons on the Hubtransports, below will do this and will move the item to a subfolder of Inbox when done

This can be run as a scheduled task as a powershell script

# Connect to Exchange server and load Exchange powershell modules
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
 
$mailbox = Get-Mailbox MailboxName
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
$s.AutodiscoverUrl($mailAddress);
 
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
$folderid = new-object  Microsoft.Exchange.WebServices.Data.Folderid([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$mailAddress)
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$folderid)
 
$mails = $inboxFolder.FindItems(20) 
$mails | % {$_.Load()}
    foreach($Item in $mails.Items)
	{ 
 
#Get the email body
$body = Get-Content “C:\scripts\CareersEmailTemplate.htm”
$body = $body -replace “Placeholder”, $Placeholder
 
#Have to convert the object to a string to use in the mail body.
[string]$msgBody = $body
 
#Create the email message and set the Subject and Body
$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $s
#Put Images inline
$message.Attachments.AddFileAttachment("C:\images\logo.png") | Out-Null
$message.Attachments[0].ContentId = "logo.png";
$message.From = “email@domain.com”
$message.Subject = “MessageSubject”
$message.Body = $msgBody
#Sets reciepients as sender
$message.ToRecipients.Add($item.Sender.Address)
 
#Send the message and save a copy in the users Sent Items folder (Alt is message.Send which will not save a copy.)
$message.SendAndSaveCopy()
 
#Move to Folder After Replying
$FolderObject = GetFolder($MailboxRoot, "\Inbox\Replied\");
		try
		{
		$Item.Move($FolderObject.Id) | out-null;
		}
		catch
		{
		Write-Host "Failed to move item", $Item.Id.UniqueId
		}
 
 
	}

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

bcc-show-all-messages[1]Recently we had a need to query emails sent to an Inbox and find out who the emails had been BCC’ed to. These would then need to be filed into folders based on the BCC address. When an email arrived in the inbox , the server striped the BCC field ( as normal ) so we had to find a way to get this value.

There are a few ways to get the BCC from a message in Exchange

We opted for the third option and below is the scheduled task

# Connect to Exchange server and load Exchange powershell modules
. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
 
$mailbox = Get-Mailbox -id mailboxname
$mailAddress = $mailbox.PrimarySmtpAddress.ToString();
 
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.1\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
$s.AutodiscoverUrl($mailAddress);
 
#Bind Root of Mailbox
$folderid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$mailAddress)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$folderid)
 
# Function to Get Folder ID from Folder Path
Function GetFolder()
{
	# Return a reference to a folder specified by path
 
	$RootFolder, $FolderPath = $args[0];
 
	$Folder = $RootFolder;
	if ($FolderPath -ne '\')
	{
		$PathElements = $FolderPath -split '\\';
		For ($i=0; $i -lt $PathElements.Count; $i++)
		{
			if ($PathElements[$i])
			{
				$View = New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
				$View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
				$View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
 
				$SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
 
				$FolderResults = $Folder.FindFolders($SearchFilter, $View);
				if ($FolderResults.TotalCount -ne 1)
				{
					# We have either none or more than one folder returned... Either way, we can't continue
					$Folder = $null;
					Write-Host "Failed to find " $PathElements[$i];
					Write-Host "Requested folder path: " $FolderPath;
					break;
				}
 
				$Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s, $FolderResults.Folders[0].Id)
			}
		}
	}
 
	$Folder;
}
 
#Bind Inbox of Mailbox
$Inboxid = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$mailAddress)
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,$Inboxid)
 
# Get x Items in Inbox
$mails = $InboxFolder.FindItems(5) 
 
    foreach($Item in $mails.Items)
	{  
	# Get list of Reciepients from Message ID that has been BCC'ed 
	$mailrecipeients = Get-MessageTrackingLog -MessageID $item.InternetMessageId | where{$_.RecipientStatus -eq "Bcc"} |% {$_.recipients}
 
		if ($mailrecipeients -match "Test@Test.com") 
		{
			$FolderObject = GetFolder($MailboxRoot, "\Moved\Folder");
			try
			{
				$Item.Move($FolderObject.Id) | out-null;
			}
				catch
			{
				Write-Host "Failed to move item", $Item.Id.UniqueId
		}
 
		}
 
 
 
	}

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)