我正在尝试执行以下操作:
StringBuilder errorList = new StringBuilder();
RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
PSSnapInInfo psinfo = runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapEx);
Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfig);
runSpace.Open();
Pipeline pipeLine = runSpace.CreatePipeline();
我收到以下错误:
No snap-ins have been registered for Windows PowerShell version 2.
我是PoweShell的新手,并不确定该错误究竟是什么意思。这是我需要安装的东西吗?
编辑:完整代码
///
/// Creates mailbox for the given user.
///
/// Email address of user.
public void EnableMailbox(string userEmail)
{
StringBuilder errorList = new StringBuilder();
RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
PSSnapInInfo psinfo = runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapEx);
Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfig);
runSpace.Open();
Pipeline pipeLine = runSpace.CreatePipeline();
if (!MailBoxAlreadyExist(userEmail, runSpace))
{
Command createMailbox = new Command("Enable-Mailbox");
createMailbox.Parameters.Add("identity", userEmail);
createMailbox.Parameters.Add("database", "Mailbox Database Name");
pipeLine.Commands.Add(createMailbox);
pipeLine.Invoke();
if (pipeLine.Error != null && pipeLine.Error.Count > 0)
{
foreach (object item in pipeLine.Error.ReadToEnd())
{
errorList.Append(item.ToString());
errorList.Append(System.Environment.NewLine);
}
Console.WriteLine(errorList.ToString());
}
}
else
{
Console.WriteLine("Mailbox of user " + userEmail + " already exists on exchange server.");
}
pipeLine.Dispose();
runSpace.Close();
runSpace.Dispose();
}
答案 0 :(得分:3)
32位和64位管理单元之间存在差异。可能是Echange只有32位,在这种情况下,将您的C#项目设置为目标平台x86。如果Exchange为64位,则仅将C#项目设置为目标平台x64。
答案 1 :(得分:2)
正如基思指出的那样,你需要合适的目标平台。 Exchange仅为64位。您需要将C#项目设置为目标平台x64。在新项目中,默认设置为x86(至少使用Visual Studio 2010)。
答案 2 :(得分:0)
您应该打开远程PowerShell会话以从c#运行PS命令。 不再支持从c#代码本地执行Exchange管理单元。 以下是枚举现有邮箱的示例:
var ExchangeCredential = new PSCredential(user, password.ToSecureString());
string serverName = string.Format("{0}.{1}", GetMachinename(), GetDomainName());
var serverUri = new Uri(String.Format("http://{0}/powershell?serializationLevel=Full", serverName));
var connectionInfo = new WSManConnectionInfo(serverUri,"http://schemas.microsoft.com/powershell/Microsoft.Exchange", ExchangeCredential);
runspace = RunspaceFactory.CreateRunspace(connectionInfo);
PowerShell psh = PowerShell.Create();
psh.Runspace = ru
Pipeline pipeline = runspace.CreatePipeline();
var command = new Command("Get-MailboxDatabase");
command.Parameters.Add(new CommandParameter("Status", true));
pipeline.Commands.Add(command);
commandResults = pipeline.Invoke();