2017-04-08 129 views

回答

2

要使用C#中,我們可以調用的PowerShell獲得Azure的AD用戶的這個屬性直接命令。您可以參考下面的代碼示例實現的目標:

private static void GetPasswordExpiredDate() 
{ 
    try 
    { 
     var userName = ""; 
     var password = ""; 
     var securePassword = new SecureString(); 
     var domainName = ""; 
     foreach (char c in password) 
     { 
      securePassword.AppendChar(c); 
     } 

     Collection<PSObject> user = null; 
     Collection<PSObject> passwordPolicy = null; 
     // Create Initial Session State for runspace. 
     InitialSessionState initialSession = InitialSessionState.CreateDefault(); 
     initialSession.ImportPSModule(new[] { "MSOnline" }); 
     // Create credential object. 
     PSCredential credential = new PSCredential(userName, securePassword); 
     // 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 getPasswordPolicy = new Command("Get-MsolPasswordPolicy"); 
     getPasswordPolicy.Parameters.Add(new CommandParameter("DomainName", domainName)); 
     //Command getUserCommand = new Command("$UserPrincipal=Get-MsolUser -UserPrincipalName '[email protected]'"); 
     Command getUserCommand = new Command("Get-MsolUser"); 
     getUserCommand.Parameters.Add(new CommandParameter("UserPrincipalName", "[email protected]")); 
     //Command getPasswordExpiredDate = new Command("$UserPrincipal.LastPasswordChangeTimestamp.AddDays($PasswordPolicy.ValidityPeriod)"); 

     using (Runspace psRunSpace = RunspaceFactory.CreateRunspace(initialSession)) 
     { 
      // Open runspace. 
      psRunSpace.Open(); 
      //Iterate through each command and executes it. 
      foreach (var com in new Command[] { connectCommand, getUserCommand, getPasswordPolicy }) 
      { 
       var pipe = psRunSpace.CreatePipeline(); 
       pipe.Commands.Add(com); 
       if (com.Equals(getUserCommand)) 
        user = pipe.Invoke(); 
       else if (com.Equals(getPasswordPolicy)) 
        passwordPolicy = pipe.Invoke(); 
       else 
        pipe.Invoke(); 
      } 
      DateTime date =(DateTime) user[0].Properties["LastPasswordChangeTimestamp"].Value; 
      UInt32 ValidityPeriod = (UInt32)passwordPolicy[0].Properties["ValidityPeriod"].Value; 
      Console.WriteLine($"The password will be expired at {date.AddDays(ValidityPeriod)}"); 
      // Close the runspace. 
      psRunSpace.Close(); 
     } 
    } 
    catch (Exception) 
    { 
     throw; 
    } 
} 
+1

您好,感謝您的答覆,以從中獲取密碼過期「LastPasswordChangeTImeStamp」我需要得到MSOL密碼policy.however用戶必須是「全球管理員「能夠檢索不合實際的密碼策略。我該如何解決這個問題? –

+0

要解決此問題,您可以使用管理員帳戶作爲代理創建服務。您可以根據自己的要求添加服務的認證/授權。 –

+0

@MandarJogalekar請隨時讓我知道,如果你仍然有這個問題的問題。 –

相關問題