C# – Sync AD Password with MS Office 365

We can change or reset Office 365 password through Microsoft 365 Online Service using powershell with C#. You need to install following components to sync Active Directory password with Office 365.

– Download and Install Microsoft Online Services Sign-In Assistant for IT Professionals RTW
– Download and Install Azure Active Directory Module for Windows PowerShell

In C# project, we need to add reference System.Management.Automation.dll to run powerShell commands.

using System.Management.Automation;
-----------------------------------
private static void ResetOffice365Password()
{
    try
    {
        string adminUser = "[email protected]";
        string adminPwd = "myadminpwd";

        //User account to sync password with office 365
        string userPrincipalName = "morgan@office365domain";
        string newPwd = "userpwd";

        string scriptText = "Import-Module MSOnline;rn" +
        "$Username=" + """ + adminUser + """ + ";rn" +
        "$Password=ConvertTo-SecureString -AsPlainText "" + adminPwd + "" -Force;rn" +
        "$Livecred = New-Object System.Management.Automation.PSCredential $Username, $Password;rn" +
        "Connect-MsolService -Credential $Livecred;rn" +
        "Set-MsolUserPassword -UserPrincipalName " + userPrincipalName + " -NewPassword "" + newPwd + "" -ForceChangePassword $false -WarningVariable warningVar -OutVariable outVar | Out-Null;rn" +
        "If ( !$warningVar -and !$Error ) { " +
        " If ( $outVar -eq "" + newPwd + "") { Echo OK; } Else { Echo Failed; } " +
        "} Else {" +
        " If ( $Error ) { Echo ERROR; $Error | fl Message; } Else { Echo WARNING; $warningVar | fl Message; }" +
        "}";

        PowerShell psExec = PowerShell.Create();
        psExec.AddScript(scriptText);
        psExec.AddCommand("Out-String");

        Collection<PSObject> results = psExec.Invoke();
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }
        Console.WriteLine(stringBuilder.ToString());
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);
    }
    Console.ReadKey();
}

Advertisement

Leave a Comment