所以,在我第二次运行它之后,我的问题是让我的函数生成它自己的数据。我第一次生成GetUsers命令,如果我的用户名和密码是正确的,它将返回与我的用户的arraylist。如果我再次运行它,无论我使用什么用户名或密码,它都将返回相同的用户。我确定我的代码非常混乱,但我一直在搞乱它试图清除它。
至于一点背景,我认为自己是一个新手程序员,所以问题很可能是非常基本的。
谢谢!
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 :(得分:0)
您是否尝试过显式删除或清空available_users类型?我不认为这是必要的,但是......