Cylindric
Cylindric

Reputation: 5894

C# Exchange PowerShell pipeLine Invoke is raising a CmdletInvocationException for null parameter values

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

Upvotes: 2

Views: 3699

Answers (2)

shabbar
shabbar

Reputation: 21

add these line to your app.config file

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

Upvotes: 2

manojlds
manojlds

Reputation: 301477

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/

Upvotes: 0

Related Questions