简体   繁体   中英

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();
  • I open a remote shell session (targetted on my local machine).
  • Add the Exchange management PsSnapIn, in order have access to the exchange commands.
  • Finally I execute my Exchange management command.

\\!/ 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM