Thursday, 14 May 2015

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 = "admin@office365domain.com";
        string adminPwd = "myadminpwd";

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

        string scriptText = "Import-Module MSOnline;\r\n" +
        "$Username=" + "\"" + adminUser + "\"" + ";\r\n" +
        "$Password=ConvertTo-SecureString -AsPlainText \"" + adminPwd + "\" -Force;\r\n" +
        "$Livecred = New-Object System.Management.Automation.PSCredential $Username, $Password;\r\n" +
        "Connect-MsolService -Credential $Livecred;\r\n" +
        "Set-MsolUserPassword -UserPrincipalName " + userPrincipalName + " -NewPassword \"" + newPwd + "\" -ForceChangePassword $false -WarningVariable warningVar -OutVariable outVar | Out-Null;\r\n" +
        "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();
}

Advertisements
Advertisements

No comments:

Post a Comment