我有一个 Windows 窗体应用程序,它使用 Powershell 和 Exchange2007 cmdlet 在 Exchange 中配置用户帐户。此应用程序只有一种形式,它为新用户获取信息,然后运行 Powershell 命令。像一个优秀的程序员一样,我只是重构了代码,把所有的 Exchange 和 Active Directory 调用都取出来,并将它们放在不同的类中。在 Windows 窗体中,我在按钮 Click 事件中调用以下代码:
ExchangeMailboxFunctions exFuncs = new ExchangeMailboxFunctions();
exFuncs.CreateNewMailbox(username, userPrincipalName, OU, txtDisplayName.Text, txtFirstName.Text, txtInitials.Text, txtLastName.Text,
txtPassword1.Text, ckbUserChangePassword.Checked, mailboxLocation);
在课堂上,我有以下内容:
RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException warning;
Runspace thisRunspace;
public ExchangeMailboxFunctions()
{
InitializePowershell();
}
private void InitializePowershell()
{
try
{
thisRunspace = RunspaceFactory.CreateRunspace(config);
config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning);
thisRunspace.Open();
}
catch (Exception ex)
{
throw new Exception(string.Format("Could not initialize Powershell: {0}", ex.Message));
}
}
public void CreateNewMailbox(string username, string userPrincipalName, string OU, string DisplayName, string FirstName, string Initials,
string LastName, string Password, bool ChangePasswordNextLogon, string MailboxLocation)
{
try
{
using (Pipeline thisPipeline = thisRunspace.CreatePipeline())
[Set a bunch of pipLine parameters here]
thisPipeline.Invoke();
}
catch (Exception ex)
thisPipeline.Invoke 导致错误,我不知道 Disposed 是什么。该代码在表单的代码隐藏中时工作得非常好。我还有一些 Active Directory 方法,我将它们撕成一个单独的类库,它们似乎工作正常。
我应该怎么做才能让这种情况停止发生?谢谢!