Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

.net - Running a powershell command in C# errors with, "Cannot invoke this function because the current host does not implement it"

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ;-)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...