4

I have an application that I use to run Exchange Powershell commands inside C# code like below. This is an example of the relevant lines I use to run the powershell command.

            RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
        PSSnapInException snapInException = null;

        //load Exchange shell
        rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException); 
        Runspace runSpace = RunspaceFactory.CreateRunspace(rsConfig);

        //open runspace
        runSpace.Open();

        //setup pipeline
        Pipeline pipeLine = runSpace.CreatePipeline();
        String sScript = "get-mailbox -identity 'rj'";

        //add script to pipeline
        pipeLine.Commands.AddScript(sScript);

        //run the script
        pipeLine.Invoke();
        pipeLine.Dispose();

This code works perfect in all cases until now. the script I am trying to run instead of the one above is to set the RetentionPolicy for a mailbox. The script I am trying to run looks like this:

Set-Mailbox -Identity 'rj' -RetentionPolicy 'Main Campus Retention Policy'

When I run this in powershell itself it works perfectly but when I try to run it using the code below I get the error, "Cannot invoke this function because the current host does not implement it."

From this error, it almost seems like the command that runs in C# cannot run the RetentionPolicy command but that doesn't make much sense. I have Googled this and tried everything suggested but no luck.

If anyone knows why this is happening, it would be very helpful.

RJ.
  • 3,173
  • 4
  • 35
  • 44

1 Answers1

11

If that command would normally prompt for confirmation then you will need to either:

  • Set -Confirm:$false as a parameter (and possibly -Force as well)
  • Set $ConfirmPreference = "None" before calling Set-Mailbox (and possibly -Force too)
  • Create a Host and implement the Confirm functionality ;-)
Jaykul
  • 15,370
  • 8
  • 61
  • 70
  • You nailed it with the -Force. It worked perfect once I added that. Thanks for the help, that completes these requirements. Awesome! – RJ. Nov 18 '10 at 21:19
  • @Kiquenet, I believe the simple answer is just to set the sScript that he's executing to: `Set-Mailbox -Identity 'rj' -RetentionPolicy 'Main Campus Retention Policy' -Confirm:$false -Force` – Jaykul Jun 13 '12 at 04:47
  • Interesting. I'll try out the -Force approach. Any ways, if you are still interested, here is the same for implementing the interfaces for PSHost, Pshostuserinterface and pshostrawuserinterface. http://stackoverflow.com/questions/1233640/capturing-powershell-output-in-c-sharp-after-pipeline-invoke-throws – Tarun Arora Jul 23 '12 at 08:35
  • `-Confirm:$false` did the trick for `Add-RecipientPermission`, too. Now I can finally add `SendAs` permissions. Thanks. – fero Jul 18 '13 at 09:05