C# - Powershell AddPSSnapin导致错误

BRo*_*ers 5 c# x86-64 powershell-2.0 system.management

所以,我导入了System.Management.Automationdll,我正在尝试New-Mailbox使用params 运行命令

所以我使用:

RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException psEx = null;
config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out psEx);
Run Code Online (Sandbox Code Playgroud)

这一切都很好,花花公子...但是当我去运行应用程序时,我得到以下内容: Cannot load Windows PowerShell snap-in Microsoft.Exchange.Management.PowerShell.E2010 because of the following error: The type initializer for 'Microsoft.Exchange.Data.Directory.Globals' threw an exception.

所以,我做了一些研究网上,我发现我需要从改变Any CPUx86作为目标平台.

但是,当我这样做时,我得到一个HTTP Error 503. The service is unavailable.错误

我几乎肯定我必须将它作为一个32位进程运行,以便它可以使用snapin(从其他读取似乎是snapin在其下运行)

我确实将应用池更改Enable 32-bit ApplicationsTrue.这是我收到错误的时候.

我已经阅读了其他帖子......但是,我不知道如何通过这Service unavailable件事.

我尝试过使用x64构建并获取 Could not load file or assembly 'EmailAdminWeb2' or one of its dependencies. An attempt was made to load a program with an incorrect format.

BRo*_*ers 3

你根本不使用这个:

config.AddPSSnapIn("your snapin here", out psEx);
Run Code Online (Sandbox Code Playgroud)

相反......只需使用如下连接:

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://yourdomainhere/Powershell/Microsoft.Exchange"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", PsCreds);
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
Run Code Online (Sandbox Code Playgroud)

现在运行您的命令就可以了。

快速注释:

  • 确保您的应用程序x64没有定位Any CPUx86
  • 如果您使用 .net 4.5(或 4),请确保应用程序池设置正确(v4.0 而不是 v2.0)并且已Enable 32bit apps设置为 false