1

我有一个 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 方法,我将它们撕成一个单独的类库,它们似乎工作正常。

我应该怎么做才能让这种情况停止发生?谢谢!

4

2 回答 2

2

确保您的代码实际上看起来像这样......

using (Pipeline thisPipeline = thisRunspace.CreatePipeline())
{
    [Set a bunch of pipLine parameters here]

    thisPipeline.Invoke();
}

括号是关键,您的示例中缺少它们。

于 2009-04-23T20:40:00.557 回答
0

抱歉,括号之类的东西实际上没问题——我一定把它们排除在问题之外了。我错过了 create 方法中的这些代码行:

 using (SecureString ss = new SecureString())
 {
    foreach (char c in Password)
      ss.AppendChar(c);
    thisPipeline.Commands[0].Parameters.Add("Password", ss);
 }

由于在调用 Invoke 之前已释放 Using,因此没有 ss,因为它已经被 Disposed。在发布这个之前应该看起来更深入一点:-(

于 2009-04-23T20:56:57.087 回答