M. Christopher
M. Christopher

Reputation: 321

C# Powershell - Exchange management {"Value cannot be null.\r\nParameter name: serverSettings"}

I want to interact with Microsoft.Exchange.Management.PowerShell.E2010 that is installed on my machine through a C# project.

My local machine is a Windows Server 2012 R2 Standard and the Exchange Server 2010 SP3 with the Rollup Update 14 is installed.

I'm using the 4.5 .NET Framework (downgrading to an older version isn't possible)

        WSManConnectionInfo connectionInfo = new WSManConnectionInfo();

        connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
        connectionInfo.OpenTimeout = 1 * 60 * 1000; // 1 minute.

        Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
        runspace.Open();
        using (PowerShell ps = PowerShell.Create())
        {
            ps.Runspace = runspace;

            ps.AddCommand("Add-PsSnapIn");
            ps.AddArgument("Microsoft.Exchange.Management.PowerShell.E2010");

            var results = ps.Invoke();

            try
            {
                ps.AddCommand("Get-MailBox");

                results = ps.Invoke();
            }
            catch (Exception e)
            {

            }
        }
        runspace.Close();

\!/ Problem is at the last step, results = ps.Invoke(); throws a System.Management.Automation.RemoteException with the message "Value cannot be null.\r\nParameter name: serverSettings".

Do you guys have any idea?

Thank you for your time.

Upvotes: 1

Views: 923

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40958

I've been fighting with this for the last couple days. I know this question is a few months old, but I thought I'd share the solution I finally found. In your .config, you need the useLegacyV2RuntimeActivationPolicy attribute set to true on the startup tag. Like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>

Using this, I was successfully able to run a Get-Mailbox command while targeting .NET 4.6.2.

Upvotes: 3

Related Questions