我被赋予了编写程序以自动创建2010交换邮箱的任务。我的研究告诉我使用powershell但我似乎无法找到要引用的命名空间,并且想要一些示例代码。我在网上找到了一些代码,但我不知道PowerShell的命名空间是什么。我认为它可能是System.Management.Automation但是当我尝试引用命名空间时,它不存在于dotnet列表中。我所拥有的只是System.Management和System.Management.Instrumentation。
任何帮助都会受到赞赏吗?
答案 0 :(得分:4)
当我这样做时,我必须单独下载Powershell,但不确定是否仍然如此。你可以从here获得它。
以下是创建邮箱的示例代码:
SecureString password = new SecureString();
string str_password = "pass";
string username = "userr";
string liveIdconnectionUri = "http://exchange.wenatex.com/Powershell?serializationLevel=Full";
foreach (char x in str_password)
{
password.AppendChar(x);
}
PSCredential credential = new PSCredential(username, password);
// Set the connection Info
WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
// create a runspace on a remote path
// the returned instance must be of type RemoteRunspace
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command.AddCommand("Enable-Mailbox");
command.AddParameter("Identity", usercommonname);
command.AddParameter("Alias", userlogonname);
command.AddParameter("Database", "MBX_SBG_01");
powershell.Commands = command;
try
{
// open the remote runspace
runspace.Open();
// associate the runspace with powershell
powershell.Runspace = runspace;
// invoke the powershell to obtain the results
return = powershell.Invoke();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// dispose the runspace and enable garbage collection
runspace.Dispose();
runspace = null;
// Finally dispose the powershell and set all variables to null to free
// up any resources.
powershell.Dispose();
powershell = null;
}
答案 1 :(得分:1)
这是一个老问题,但它可能会对未来的访客有所帮助......
w69rdy的回答对我不起作用。但我得到了它的工作,并在此处发表了博客http://pedroliska.wordpress.com/2011/07/22/running-exchange-management-shell-commands-powershell-with-c/