2

I am trying to get a simple PowerShell command output into C#, using the functionality found in the System.Management.Automation namespace.

I have the Exchange console on my machine, and can issue commands successfully from the console, but from C# I get an error I don't understand.

Here's the sample code that should get some simple server information:

static void Main(string[] args)
{
    RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
    PSSnapInException snapInException = null;
    PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);

    using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig))
    {
        myRunSpace.Open();

        using (Pipeline pipeLine = myRunSpace.CreatePipeline())
        {
            Command serverCommand = new Command("Get-MailboxServer");

            pipeLine.Commands.Add(serverCommand);
            Collection<PSObject> server = pipeLine.Invoke();
            foreach (PSObject cmdlet in server)
            {
                string cmdletName = cmdlet.Properties["Name"].Value.ToString();
                Console.WriteLine(cmdletName);
            }
        }
    }
}

The actual error occurrs on the pipeLine.Invoke() line:

System.Management.Automation.CmdletInvocationException was unhandled
Value cannot be null.
Parameter name: parameters
Source=System.Management.Automation

I have tried adding parameters, for example the server Identity, but the same thing happens:

using (Pipeline pipeLine = myRunSpace.CreatePipeline())
{
    Command serverCommand = new Command("Get-MailboxServer");
    serverCommand.Parameters.Add("Identity", mbServerName);
    pipeLine.Commands.Add(serverCommand);
    Collection<PSObject> server = pipeLine.Invoke();
}
1
  • I see that you're not checking snapInException or info. Is it possible that the rsConfig.AddPSSnapIn call is failing? Dec 7, 2011 at 17:41

2 Answers 2

2

add these line to your app.config file

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
</startup>
0

I replaced the command with Get-Process and it works fine. It seems to be an issue with how the exchange cmdlets work ( even though Get-Mailboxserver also has a variant that doesn't take in any parameter.)

This thread talks about the issue and proposes an alternate solution: http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/48da1346-f47e-4ba9-9747-428fe07b4492/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.