Thursday, February 25, 2010

Create a folder under the Inbox if one doesn't existing using Powershell and the EWS Managed API

I've covered this one before using other Exchange API's and versions but here's a potentially useful script if you want to create a folder in a Mailbox with a powershell/EWS script. To avoid any errors it does a search of the target folder where your going to create the subfolder first. Although this isn't 100% needed as the error you will get if it does exist is pretty self explanatory its good practice to do this anyway

The script like many others I've posted uses the currently logged on user to then access another mailbox using Delegate access. I've included two versions one is feed via the Get-Mailbox cmdlet so this could potentially be used to add a folder for every mailbox on a particular server (as long as you have rights). I've put a download of the script here the script which if feed via get-mailbox looks like

function CreateFolder($MailboxName) {
"Mailbox Name : " + $MailboxName
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$ibInboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$newFolderName)
$findFolderResults = $service.FindFolders($ibInboxFolder.Id,$SfSearchFilter,$fvFolderView)
if ($findFolderResults.TotalCount -eq 0){
"Doesn't Exist"
$NewFolder = new-object Microsoft.Exchange.WebServices.Data.Folder($service)
$NewFolder.DisplayName = $newFolderName
# $NewFolder.Save($ibInboxFolder.Id.UniqueId)
"Folder Created"
}
else{
"Folder Already Exist - Do Nothing"
}
}


$newFolderName = "mynewfolder123"

$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)
$frun = $true


Get-mailbox | foreach-object {
$WindowsEmailAddress = $_.WindowsEmailAddress.ToString()
if ($frun -eq $true) {
$frun = $false
$service.AutodiscoverUrl($WindowsEmailAddress)
}
CreateFolder($WindowsEmailAddress)