我正在尝试使用 C# 同时查询两个不同 Office 365 帐户的用户。从两个 Powershell Windows 尝试或通过代码连接并获取一个又一个帐户时,它工作正常。但是在同时使用代码时不起作用。
在检查时我发现从 C# 尝试时只生成一个日志文件。但是从 PowerShell 窗口尝试时会生成两个不同的日志文件。
日志文件夹位置:%userprofile%\appdata\Local\Microsoft\Office365\Powershell
这意味着从代码运行时,即使有两个运行空间,它也像使用单个 PowerShell 窗口运行一样工作。
主要方法代码:
Thread t1 = new Thread(() => connectandExec("admin@domain1.onmicrosoft.com", "Pwdd@123"));
Thread t2 = new Thread(() => connectandExec("admin@domain2.onmicrosoft.com", "Pwdd@123"));
t1.Start();
t2.Start();
连接并获取用户的方法:
public static void connectandExec(String userName, String password) {
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new String[] { "MSOnline" });
Runspace runspace = RunspaceFactory.CreateRunspace(iss);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
Command cmd = new Command("Connect-MsolService");
System.Security.SecureString pwd = new System.Security.SecureString();
foreach (Char c in password.ToCharArray()) {
pwd.AppendChar(c);
}
log("Connecting to : " + userName);
PSCredential pscred = new PSCredential(userName, pwd);
cmd.Parameters.Add("Credential", pscred);
ps.Commands.AddCommand(cmd);
ps.Invoke();
if (ps.Streams.Error.Count > 0) {
log("Error when connecting: " + userName);
foreach (ErrorRecord errRecord in ps.Streams.Error) {
log(userName + errRecord.ToString());
}
} else {
log("Connected to : " + userName);
}
ps.Commands.Clear();
try {
ps.Commands.AddScript("Get-MsolUser -All");
ICollection<PSObject> results = ps.Invoke();
if (ps.Streams.Error.Count > 0) {
log("Error when getting users: " + userName);
foreach (ErrorRecord errRecord in ps.Streams.Error) {
log(userName + errRecord.ToString());
}
} else {
foreach (PSObject obj in results) {
if (obj != null && obj.ToString() != "") {
Object val = obj.Members["UserPrincipalName"].Value;
if (val != null) {
log(userName + ":" + val.ToString());
}
}
}
}
} catch (Exception ex) {
log(userName + ":Exception during getUsers: " + ex.ToString());
}
}