How do I create an Outlook rule in PowerShell that moves email to a folder without an error, using the same code that works in C# perfectly?

Viewed 529

I'm trying to write PowerShell code to create an Outlook rule to move an email, and it isn't working.

Note that I do not have access to the server, so the *-InboxRule cmdlets like New-InboxRule aren't available.

There's something wonky going on with the COM interop between PowerShell and Outlook, because it works perfectly in C#, but the identical code in PowerShell doesn't.

Here's the C# code, which works perfectly:

Microsoft.Office.Interop.Outlook.Application outlook = null;

try
{
    outlook = (Microsoft.Office.Interop.Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
}
catch
{
}

if (outlook == null)
{
    outlook = new Microsoft.Office.Interop.Outlook.Application();
}

var inbox = outlook.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
var oMoveTarget = inbox.Folders["MoveTarget"];

// debugging
Console.WriteLine(inbox.FolderPath.ToString());
Console.WriteLine(oMoveTarget.FolderPath.ToString());

var rules = outlook.Session.DefaultStore.GetRules();
Console.WriteLine(string.Format("There are {0} rules", rules.Count));

var name = string.Format("Rule {0}", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
var rule = rules.Create(name, Microsoft.Office.Interop.Outlook.OlRuleType.olRuleReceive);

// conditions
rule.Conditions.From.Recipients.Add("John Smith");
rule.Conditions.From.Recipients.ResolveAll();
rule.Conditions.From.Enabled = true;

// actions
rule.Actions.MoveToFolder.Folder = oMoveTarget;
rule.Actions.MoveToFolder.Enabled = true;
rules.Save(true);

Now, here's the identical (other than language syntax) PowerShell code:

try
{
    $outlook = [Runtime.InteropServices.Marshal]::GetActiveObject("Outlook.Application");
}
catch
{
}

if ($outlook -eq $null)
{
    $outlook = New-Object -ComObject Outlook.Application
}

$inbox = $outlook.Application.Session.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox);
$oMoveTarget = $inbox.Folders["MoveTarget"];

# debugging
[Console]::WriteLine($inbox.FolderPath.ToString());
[Console]::WriteLine($oMoveTarget.FolderPath.ToString());

$rules = $outlook.Session.DefaultStore.GetRules();
[Console]::WriteLine([string]::Format("There are {0} rules", $rules.Count));

$name = [string]::Format("Rule {0}", [DateTime]::Now.ToString("yyyyMMdd_HHmmss"));
$rule = $rules.Create($name, [Microsoft.Office.Interop.Outlook.OlRuleType]::olRuleReceive);

# conditions
$rule.Conditions.From.Recipients.Add("John Smith");
$rule.Conditions.From.Recipients.ResolveAll();
$rule.Conditions.From.Enabled = $true;

# actions
$rule.Actions.MoveToFolder.Folder = $oMoveTarget;
$rule.Actions.MoveToFolder.Enabled = $true;
$rules.Save($true);

While the C# code succeeds, the PS code fails with:

One or more rules cannot be saved because of invalid actions or conditions.
At line:1 char:1
+ $rules.Save($true);
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
 

Upon further investigation, it's basically caused by this line, which isn't actually doing anything:

$rule.Actions.MoveToFolder.Folder = $oMoveTarget;

When I run the C# equivalent, if I immediately turn around and look at that property, it is set. However, in PowerShell, it doesn't throw an error or anything... it just silently does nothing.

How can I get this to work? Please help!

2 Answers

You can do this with:

# actions
$action = $rule.Actions.MoveToFolder
$action.Enabled = $true

[Microsoft.Office.Interop.Outlook.MoveOrCopyRuleAction].InvokeMember("Folder",[Reflection.BindingFlags]::SetProperty, $null, $action, $oMoveTarget) 

You can run C# code in powershell. Is there a requirement to rewrite it in powershell?

$code = @'
using System;

namespace Outlook
{
    public class Outlook
    {
        public static void Main(){
            Microsoft.Office.Interop.Outlook.Application outlook = null;

            try
            {
                outlook = (Microsoft.Office.Interop.Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
            }
            catch
            {
            }

            if (outlook == null)
            {
                outlook = new Microsoft.Office.Interop.Outlook.Application();
            }

            var inbox = outlook.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            var oMoveTarget = inbox.Folders["TargetFolder"];

            // debugging
            Console.WriteLine(inbox.FolderPath.ToString());
            Console.WriteLine(oMoveTarget.FolderPath.ToString());

            var rules = outlook.Session.DefaultStore.GetRules();
            Console.WriteLine(string.Format("There are {0} rules", rules.Count));

            var name = string.Format("Rule {0}", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
            var rule = rules.Create(name, Microsoft.Office.Interop.Outlook.OlRuleType.olRuleReceive);

            // conditions
            rule.Conditions.From.Recipients.Add("John Smith");
            rule.Conditions.From.Recipients.ResolveAll();
            rule.Conditions.From.Enabled = true;

            // actions
            rule.Actions.MoveToFolder.Folder = oMoveTarget;
            rule.Actions.MoveToFolder.Enabled = true;
            rules.Save(true);
        }
    }
}
'@

$assemblies = ("Microsoft.Office.Interop.Outlook")

Add-Type -ReferencedAssemblies $assemblies  -TypeDefinition $code -Language CSharp

[Outlook.Outlook]::Main()
Related