Powershell と Exchange2007 コマンドレットを使用して Exchange でユーザー アカウントをプロビジョニングする Windows フォーム アプリがあります。このアプリケーションには、新しいユーザーの情報を取得して Powershell コマンドを実行するフォームが 1 つだけあります。優れたプログラマーのように、コードをリファクタリングし、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 メソッドもいくつかありますが、それらは正常に動作しているようです。
これが起こらないようにするにはどうすればよいですか?ありがとう!