locked
Exchange Powershell via C# RRS feed

  • Question

  • Hi,

     

    I am trying to run some commands via Powershell in C# in Exchange.  But each time I run an Exchange command I get the error that the command is not a recognizable cmdlet, function, etc.

     

    Here is what I am doing;

     

    RunspaceConfiguration config = RunspaceConfiguration.Create();

    PSSnapInException snapEx = null;

    PSSnapInInfo info = config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);

    Runspace space = RunspaceFactory.CreateRunspace(config);

    Command createcmd = new Command(@"Get-Mailboxstatistics testbox");

    pipe.Commands.Add(createcmd);

    Collection<PSObject> results = null;

    try

    {

    results = pipe.Invoke();

    }

    catch (Exception ex)

    {

    System.Diagnostics.Debug.WriteLine(ex.Message.ToString());

    }

     

    When I run the the Get-Mailboxstatistics via Powershell it works no problem.  The only command I am able to run via C# successfully is Get-Command (which does list all of the Exchange commands).  It is as if I am not connected to the Exchange SnapIn when running my code.

     

    I am running this example directly on the Exchange2007 server.

     

    Is there something I am missing here?

     

    Thank you - Greg.

    Tuesday, October 14, 2008 2:00 PM

Answers

  • I resolved the issue.

     

    When executing a cmdlet with parameters you need to use the parameters collection (not that format them into the main command string).

     

    Once I did this I was able to execute things smoothly.

     

    So the only changes in the above code is;

    Command createcmd = new Command(@"Get-Mailboxstatistics");

    createcmd.Parameters.Add("server", "servername");

     

    I read some articles on issues running the powershell scripts from a debugging session with VS2005.  I did not have this issue.

     

    Greg.

    Tuesday, October 14, 2008 2:52 PM