Hey, Scripting Guy! Can I Use Windows PowerShell to Create a New Outlook Inbox Rule?

Hey, Scripting Guy! Can I Use Windows PowerShell to Create a New Outlook Inbox Rule?

  • Comments 10
  • Likes

Bookmark and Share

 

Hey, Scripting Guy! Question

Hey Scripting Guy! I would absolutely love to see a Windows PowerShell script that would create a new inbox rule in Microsoft Outlook. I have looked all over the Internet and have come up blank. I have asked friends, and people at work and no one seems to know how to do this. I am not sure it can actually be accomplished, but I figure if anyone can do it, you can! By the way, I loved your article about creating folders in Outlook and thought it was incredibly helpful. That is what gave me the idea to write. If you don’t take requests, I completely understand. You must get thousands.

-- PC

 

Hey, Scripting Guy! Answer Hello PC,

Microsoft Scripting Guy Ed Wilson here. It is a wonderful day—and it will only get better. I am getting ready to go on holiday for 10 days. I have only one meeting today, and I have had time to answer a few vital e-mails and create my out of office (OOF) reply. Because it is such a great day, I took the time to write a pretty cool script for my OOF. It is called Start-Vacation.ps1 and is seen here. (You therefore get two scripts for the price of one today, an amazing holiday bargain.)

Start-Vacation.ps1

Function Start-Vacation
{
 Param($user,$start, $stop, $contact)
 $oof = New-Object psobject
 $oof | Add-Member -MemberType noteProperty -Name userName -Value $user
 $oof | Add-Member -MemberType noteProperty -Name startdate -Value $start
 $oof | Add-Member -MemberType noteProperty -Name enddate -Value $stop
 $oof | Add-Member -MemberType noteProperty -Name ScriptCenterContact -Value $contact
 $oof | Add-Member -MemberType noteProperty -Name Email -Value $false
 $oof | Add-Member -MemberType noteProperty -Name Phone -Value $false
 $oof | Add-Member -MemberType noteProperty -Name FaceBook -Value $false
 $oof | Add-Member -MemberType noteProperty -Name Twitter -Value $false
 $oof
} #end function Start-Vacation

# *** start script ***

$oof = Start-vacation -user "EdWilson" -start "12/5/2009" -stop "12/15/2009" `
     -contact "CraigLiebendorfer"
"Microsoft Scripting Guy Ed Wilson is on vacation ..."
$oof

I have a function called Start-Vacation that accepts four input parameters: the user name, start dates, stop dates, and the person to contact while I am away. Inside the Start-Vacation function, I create a custom psobject and add several noteProperties to the object. The last thing I do in the function is return the custom object to the calling script. The script itself begins by calling the Start-Vacation function, passing the appropriate parameters, and capturing the custom psobject in the $oof variable. The script then displays that object. The results from running the script are shown here:

Microsoft Scripting Guy Ed Wilson is on vacation ...


userName            : EdWilson
startdate           : 12/5/2009
enddate             : 12/15/2009
ScriptCenterContact : CraigLiebendorfer
Email               : False
Phone               : False
FaceBook            : False
Twitter             : False

PC, a wonderful day does not automatically happen. My wonderful day actually started three days ago when I wrote the CreateOutLookRule.ps1 in answer to your question about creating Outlook rules via script. Unfortunately, when I ran the CreateOutlookRule.ps1 script on my laptop, it did not work. It kept giving me a type mismatch error when it attempted to add the rule. Therefore, I tested, revised, retested, and was getting nowhere. Finally, I caught Stephanie who is a PFE in Florida on Office Communicator and asked her to look at the script. I also sent the script to James who is a test engineer on the Windows PowerShell team in Redmond, and to George who is a PFE in Quebec. Everyone said, “Bummer it does not work” except for George who said, “Cool, it works great.” He then asked me if I was running the beta of Outlook 2010. “Of course I am,” I said. “Aren’t you?” As it turns out, he is running Office 2007 on his laptop, and the script worked perfectly.

I then built an Exchange 2010 server and a client workstation running Windows 7 and Office 2007 to test his findings. As it turns out, the script does work perfectly. I then filed a bug with the Microsoft Office team.

James, the consummate professional, also tested an additional scenario—Outlook 2007 with Project 2010 installed. That scenario also fails, so it seems if you have any beta Office 2010 product installed, the script will fail. Hopefully, the automation bug will get fixed before the final release because the CreateOutlookRule.ps1 script really is cool.

PC, the complete CreateOutlookRule.ps1 script is seen here.

CreateOutLookRule.ps1

#Requires -version 2.0
Add-Type -AssemblyName microsoft.office.interop.outlook
$olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
$olRuleType = "Microsoft.Office.Interop.Outlook.OlRuleType" -as [type]
$outlook = New-Object -ComObject outlook.application
$namespace  = $Outlook.GetNameSpace("mapi")
$inbox = $namespace.getDefaultFolder($olFolders::olFolderInbox)
$MoveTarget = $inbox.Folders.item("FromBob")
$rules = $outlook.session.DefaultStore.GetRules()
$rule = $rules.Create("MyNewRule",$olRuleType::OlRuleReceive)
$FromCondition = $rule.Conditions.From
$FromCondition.Enabled = $true
$FromCondition.Recipients.Add("bob")
$fromCondition.Recipients.ResolveAll()
$MoveRuleAction = $rule.actions.MoveToFolder
$MoveRuleAction.Folder = $Movetarget
$MoveRuleAction.Enabled = $true
$rules.Save()

The first thing the CreateOutlookRule.ps1 script does is use the Add-Type cmdlet to load the outlook interop assembly. Next it adds the OlDefaultFolders and the OlRuleType type enumerations and stores them in the $olFolders and $olRuleType variables. For more information about working with the Add-Type cmdlet or type enumerations, see Monday’s Hey, Scripting Guy! article. The code that loads the interop assembly and type enumerations is seen here:

#Requires –version 2.0

Add-Type -AssemblyName microsoft.office.interop.outlook

$olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]

$olRuleType = "Microsoft.Office.Interop.Outlook.OlRuleType" -as [type]

The next thing that is done in the CreateOutlookRule.ps1 script is to load the Outlook application COM object. This is accomplished by using the New-Object cmdlet. The returned application object is stored in the $outlook variable. The GetNameSpace method is used from the application object to return a namespace object that is stored in the $namespace variable. This is shown here:

$outlook = New-Object -ComObject outlook.application

$namespace  = $Outlook.GetNameSpace("mapi")

Then the GetDefaultFolder method from the namespace object is used to return a folder object. The olFolderInbox enumeration value is passed to the GetDefaultFolder method. The resulting folder object is stored in the $inbox variable, as seen here:

$inbox = $namespace.getDefaultFolder($olFolders::olFolderInbox)

After you have a folder object, the folders property of the folder object is used to return a folders collection. The folders collection contains the item method that takes the name of an existing folder in your Outlook profile. In this example, I used the Outlook application to create a folder named FromBob before running the script. This made sense to me because the Outlook rule I am going to create will move e-mails from a user named Bob to the FromBob folder. The reference to the FromBob folder object is stored in the $MoveTarget variable, as shown here:

$MoveTarget = $inbox.Folders.item("FromBob")

To create a new rule in Microsoft Outlook, you need to first obtain a rules object. The easiest way to obtain a rules object is to use the GetRules method from a store object. To obtain the store object, use the DefaultStore property from a session object. The session object is obtained from the Session property of the Outlook Application object. The rules object is stored in the $rules variable, as shown here:

$rules = $outlook.session.DefaultStore.GetRules()

After you have a rules object, you can use the Create method to create a new rule. The Create method requires two parameters: the first is a string that represents the name of the new rule, and the second parameter is the type of rule to create. For the CreateOutLookRule.ps1 script, I am creating a rule that is appliedwhen a new e-mail is received; therefore, I use the OlRuleReceive enumeration from the OlRuleType enumeration. There are many other types of rules that can be created by using a different enumeration value for this parameter. Store the new rule object that is created by the Create method in the $rule variable, as shown here:

$rule = $rules.Create("MyNewRule",$olRuleType::OlRuleReceive)

Now it is time to fill out the parameters for the new rule. These correspond to the parameters you can supply from the Rules and Alerts wizard that is available in Outlook 2007. Because I want the rule to be triggered when an e-mail contains a specific name in the From property, I specify the From condition, and store the returned Condition object in the $FromCondition variable. The exact configuration of condition properties that are used depends on the type of Condition object that you create. Of course, all rules will need to be enabled by setting the Enabled property to $true, as seen here:

$FromCondition = $rule.Conditions.From

$FromCondition.Enabled = $true

A recipient is added and resolved by using the Add method and the ResolveAll method from the Recipient object, as seen here.

$FromCondition.Recipients.Add("bob")

$fromCondition.Recipients.ResolveAll()

The MoveToFolder action object is created and stored in the $MoveRuleAction variable. The Folder property is used to specify the target of the Move operation, and it receives the Folder object stored in the $Movetarget variable. When this is completed, the action is enabled by setting the Enabled property equal to $true, as shown here:

$MoveRuleAction = $rule.actions.MoveToFolder

$MoveRuleAction.Folder = $Movetarget

$MoveRuleAction.Enabled = $true

When everything has been configured properly, the newly created rule is saved by calling the Save method from the rules object, as shown here:

$rules.Save()

The newly created rule can be seen in Microsoft Outlook 2007 by clicking Rules and Alerts in the Tools menu. This is shown here:

Image of newly created rule

 

PC that is all there is to creating an inbox rule in Outlook using Windows PowerShell. Microsoft Outlook Week will continue tomorrow.

If you want to know exactly what we will be looking at tomorrow, follow us on Twitter or Facebook. If you have any questions, send e-mail to us at scripter@microsoft.com or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson and Craig Liebendorfer, Scripting Guys

                                                                                                                                     

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • I get the type mismatch error in both Outlook 2007 and 2010.

    Have you figured out a solution/workaround to this yet?

  • How could you use this method to send a message from powershell?

  • Great postm, and it works a charm.  I am trying to adapt this code to a client side rule on rss fields...  for example, I want to create a rule that "from any RSS Feed" "displays _ in the new item alert window" and am having a heck of time getting the syntax right.. any hints?

  • I also got the ComObject mismatch error and came up with a solution. You can find it here: dandarache.wordpress.com/.../using-powershell-to-create-rules-in-outlook

  • Script to create a rule for "RSS feed" with "Desktop Alert". I took Dan Jansson's script and modified to fit my needs:

    ##########################################

    # Based on PowerShell 2.0

    ##########################################

    function add_outlook_rule

    {

       param([string]$RuleName,

             [string]$RedirectFolder,

             [string[]]$Title)

       Add-Type -AssemblyName microsoft.office.interop.outlook

       $olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]

       $olRuleType = "Microsoft.Office.Interop.Outlook.OlRuleType" -as [type]

       $outlook = New-Object -ComObject outlook.application

       $namespace  = $Outlook.GetNameSpace("MAPI")

       $inbox = $namespace.getDefaultFolder($olFolders::olFolderInbox)

       $RSSFeeds = $namespace.getDefaultFolder($olFolders::olFolderRSSFeeds)

       $rules = $outlook.session.DefaultStore.GetRules()

       $rule = $rules.Create($RuleName,$olRuleType::OlRuleReceive)

       $d = [System.__ComObject].InvokeMember(

           "EntryID",

           [System.Reflection.BindingFlags]::GetProperty,

           $null,

           $RSSFeeds.Folders.Item($RedirectFolder),      

           $null)

       $MoveTarget = $namespace.getFolderFromID($d)

       $MoveRuleAction = $rule.Actions.MoveToFolder

       [Microsoft.Office.Interop.Outlook._MoveOrCopyRuleAction].InvokeMember(

           "Folder",

           [System.Reflection.BindingFlags]::SetProperty,

           $null,

           $MoveRuleAction,

           $MoveTarget)

       $MoveRuleAction.Enabled = $true

       $DisplayAlert =  $rule.Actions.DesktopAlert

       $DisplayAlert.Enabled = $true

       $RSSFeedCondition = $rule.Conditions.FromRssFeed

       $RSSFeedCondition.Enabled = $true

       $RSSFeedCondition.FromRssFeed = $Title

       $rules.Save()

       #$olFolder1 = $namespace.Folders.Item(1).Folders.Item("RSS Feeds").Folders.Item($RedirectFolder)

       #$olFolder1.AddToFavorites

    }

    ##########################################

    # SYNTAX:

    ##########################################

    # add_outlook_rule RULENAME

    #                  MOVETOFOLDER

    #                  Title

    ##########################################

    add_outlook_rule "MyRssFeedRule" "Target Feed Folder" @("Feed TitleWord1","Feed TitleWord2")

  • @Sumit Dadhwal this is great. Can you upload it to the script center script repository? gallery.technet.microsoft.com/scriptcenter

  • If you are an Exchange admin you can use the New-InboxRule and Set-MailboxAutoReplyConfiguration cmdlets and set/modify these on a user's behalf

  • I am trying get the Start-Vacation one to work.  Hate to sound stupid, but which part of the code is actually in the start-vacation.ps1 file and how do we actually kick off the file?

  • thanks

  • I guess I'm missing something. In the first part you created a script to create an $oof message. Then in the second part you talk about creating a rule. I'm just not seeing the "glue" that binds these together.