C# 从ADUser获取用户主体
我有一个ADUSER列表,但对于每个ADUSER,我希望获得其属性“LastPasswordSet”,该属性只能通过UserPrincipal访问(不确定是否还有其他方法) 如果我使用这个代码C# 从ADUser获取用户主体,c#,.net,active-directory,ldap,C#,.net,Active Directory,Ldap,我有一个ADUSER列表,但对于每个ADUSER,我希望获得其属性“LastPasswordSet”,该属性只能通过UserPrincipal访问(不确定是否还有其他方法) 如果我使用这个代码 PrincipalContext l_objContext = new PrincipalContext(ContextType.Domain, l_strDomain, l_strUserOU); foreach (ADUser ADuser in Users) {
PrincipalContext l_objContext = new PrincipalContext(ContextType.Domain, l_strDomain, l_strUserOU);
foreach (ADUser ADuser in Users)
{
UserPrincipal usr = UserPrincipal.FindByIdentity(l_objContext, ADuser.CommonName.ToString());
if (usr.LastPasswordSet.HasValue)
{
EmailString(usr.LastPasswordSet.ToString());
}
}
现在我不想向UserPrincipal提供任何东西,而不是ADUSER的任何属性,上面的代码也不起作用,问题是它发送了几封电子邮件,然后在它给出的某个地方遇到错误,服务停止,这可能是因为某个未验证的日期(我不想修复它,只是声明以便您了解我在做什么)您可以创建自己的
PrincipalContext
,然后使用UserPrincipal.FindByIdentity
获取主体。从这里,我想您已经知道,您可以调用LastPasswordSet
属性
public static DateTime? GetLastPasswordSet(string domain, string userName)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
return userPrincipal.LastPasswordSet;
}
}
注意:您需要添加对System.DirectoryServices.AccountManagement
[编辑:回答评论中的进一步问题]
要测试密码是否在一个月前最后一次设置,请执行以下操作:
if (lastPasswordSet < DateTime.Now.AddMonths(-1))
{
// Password last set over a month ago.
}
if(lastPasswordSet
需要记住的一件事是,一个月是一个模棱两可的时间长度——它的长度取决于月份(和年份)您处于中。根据您尝试执行的操作,可能更适合使用固定期限,例如28天。您可以创建自己的
PrincipalContext
,然后使用UserPrincipal.FindByIdentity
获取主体。从这里,我想您已经知道,您可以调用LastPasswordSet
属性y
public static DateTime? GetLastPasswordSet(string domain, string userName)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
return userPrincipal.LastPasswordSet;
}
}
注意:您需要添加对System.DirectoryServices.AccountManagement
[编辑:回答评论中的进一步问题]
要测试密码是否在一个月前最后一次设置,请执行以下操作:
if (lastPasswordSet < DateTime.Now.AddMonths(-1))
{
// Password last set over a month ago.
}
if(lastPasswordSet
需要记住的一件事是,一个月是一个模棱两可的时间长度——它的长度取决于月份(和年份)您已进入。根据您尝试执行的操作,可能更适合使用固定期限,例如28天。您的问题似乎与此问题类似-我已经检查了该问题,但他们正在使用UserPrincipal更改其值,如果您再次阅读我的问题,它会显示如何使用UserPrincipal获取UserPrincipalADUser属性…似乎你的问题与此类似-我已经检查了这个问题,但他们正在使用UserPrincipal更改其值,如果你再次阅读我的问题,它会说如何使用ADUser属性获取UserPrincipal…我如何将此属性与当前日期进行比较,并查看其是否比从今天起的一个月如何将此属性与当前日期进行比较,并查看其是否比从今天起的一个月更旧