2012-04-26 113 views
0

所以,我有一個問題讓我的函數在第二次運行後生成它自己的數據。我第一次生成GetUsers命令,只要我的用戶名和密碼是正確的,它就會返回一個數組列表給我的用戶。如果我再次運行它,不管用戶使用什麼用戶名或密碼,它都會返回相同的用戶。我確信我的代碼非常混亂,但我一直在試圖弄清楚它。爲什麼Powershell不清除?

至於一點背景,我認爲自己是一個新手程序員,所以這個問題很可能是一個非常基本的東西。

謝謝!

public ArrayList GetUsers(string user, string pass) 
     { 
      InitialSessionState iss = InitialSessionState.CreateDefault(); 

      iss.ImportPSModule(new[] { "MSOnline" }); 
      using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss)) 
      { 
       myRunSpace.Open(); 
       using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create()) 
       { 
        ArrayList available_users = new ArrayList(); 

        //create Powershell runspace 

        powershell.Runspace = myRunSpace; 

        Command connect = new Command("Connect-MsolService"); 
        System.Security.SecureString secureString = new System.Security.SecureString(); 
        string myPassword = pass; 
        foreach (char c in myPassword) 
         secureString.AppendChar(c); 

        connect.Parameters.Add("Credential", new PSCredential(user, secureString)); 
        powershell.Commands.AddCommand(connect); 

        Collection<PSObject> results = null; 
        results = powershell.Invoke(); 
        powershell.Commands.Clear(); 

        Command getuser = new Command("Get-MsolUser"); 
        powershell.Commands.AddCommand(getuser); 
        results = null; 

        powershell.Stop(); 

        results = powershell.Invoke(); 

        foreach (PSObject item in results) 
        { 
         string userprincipalname = item.Properties["UserPrincipalName"].Value as string; 
         available_users.Add(userprincipalname); 
        } 

        powershell.Dispose(); 
        myRunSpace.Dispose(); 

        powershell.Runspace.Dispose(); 
        powershell.Runspace.Close(); 
        myRunSpace.Close(); 
        return available_users; 
       } 
      } 
     } 
+0

關於它的完整源代碼的任何最終解決方案? – Kiquenet 2012-06-01 10:38:42

回答

0

您是否試過顯式刪除或清空available_users類型?我不認爲這是必要的,但...

相關問題