I am trying to reset password for Office365 users concurrently from thread(C#).
First connect to the Office365 using Connect-MsolService and then reset password using Set-MsolUserPassword commandlets.
While executing the commandlet Connect-MsolService, below exception is thrown.
Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown.
But the user assigned in the last thread, works fine.
Whether Office365, does not support multiple connections?. Please let me know the correct way to do this concurrently.
Office365UserCredential credential = new Office365UserCredential("admin@XXXX.onmicrosoft.com", "XXXXXXXX"); Thread t1 = new Thread(() => Office365ManageUsers.ResetPassword("test1@XXXX.onmicrosoft.com", "XXXXXXXX", false, credential)); t1.Start(); <=====Fails Thread t2 = new Thread(() => Office365ManageUsers.ResetPassword("test3@XXXX.onmicrosoft.com", "XXXXX", false, credential)); t2.Start(); <=====Password reset operation is success
public static bool ResetPassword(string userName, string newPassword, bool isChangePasswordOnNextLogon, Office365UserCredential userCredentials) { bool status = true; try { // Create Initial Session State for runspace. InitialSessionState initialSession = InitialSessionState.CreateDefault(); initialSession.ImportPSModule(new[] { "MSOnline" }); // Create credential object. PSCredential credential = new PSCredential(userCredentials.UserName, userCredentials.Password); // Create command to connect office 365. Command connectCommand = new Command("Connect-MsolService"); connectCommand.Parameters.Add((new CommandParameter("Credential", credential))); // Create command to get office 365 users. Command resetPasswordCommand = new Command("Set-MsolUserPassword"); resetPasswordCommand.Parameters.Add((new CommandParameter("UserPrincipalName", userName))); resetPasswordCommand.Parameters.Add(new CommandParameter("NewPassword", newPassword)); resetPasswordCommand.Parameters.Add(new CommandParameter("ForceChangePassword", isChangePasswordOnNextLogon)); using (Runspace psRunSpace = RunspaceFactory.CreateRunspace(initialSession)) { // Open runspace. psRunSpace.Open(); //Iterate through each command and executes it. foreach (var com in new Command[] { connectCommand, resetPasswordCommand }) { var pipe = psRunSpace.CreatePipeline(); pipe.Commands.Add(com); // Execute command and generate results and errors (if any). Collection<PSObject> results = pipe.Invoke(); var error = pipe.Error.ReadToEnd(); if (error.Count > 0 && com == connectCommand) { status = false; } if (error.Count > 0 && com == resetPasswordCommand) { status = false; } } psRunSpace.Close(); } } catch (Exception) { status = false; throw; } return status; }