所以,我在第二次运行它后让我的函数生成它自己的数据时遇到了问题。第一次生成 GetUsers 命令时,如果我的用户名和密码正确,它将返回一个包含我的用户的数组列表。如果我再次运行它,无论我使用什么用户名或密码,它都会返回相同的用户。我确定我的代码很混乱,但我一直在搞乱它试图让它变得清晰。
至于一点背景,我认为自己是一个新手程序员,所以这个问题很可能是一些非常基本的问题。
谢谢!
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;
}
}
}