使用 C# 进行 AD 请求

发布于 2025-01-09 07:15:07 字数 728 浏览 0 评论 0原文

我试图使用以下代码从 AD 获取所有用户及其密码到期日期,但出现错误。

System.InvalidOperationException:“调用此方法之前必须保留主体对象。”

代码:

PrincipalContext domain = new PrincipalContext(ContextType.Domain,"AAA","OU=USERS,OU=TEST,DC=AAA,DC=AA, DC=A");
UserPrincipal user = new UserPrincipal(domain);
PrincipalSearcher pS = new PrincipalSearcher(user);

foreach (UserPrincipal result in pS.FindAll())
    {
    if (result != null && result.DisplayName != null)
        {
        DirectoryEntry entry = (DirectoryEntry)user.GetUnderlyingObject();
        IADsUser native = (IADsUser)entry.NativeObject;
        Console.WriteLine(result.DisplayName, native.PasswordExpirationDate);
        }
     }

I'm trying to get all users from AD and their passwords expiration dates with the following code, but got the error.

System.InvalidOperationException: 'The Principal object must be persisted before this method can be called.'

The code:

PrincipalContext domain = new PrincipalContext(ContextType.Domain,"AAA","OU=USERS,OU=TEST,DC=AAA,DC=AA, DC=A");
UserPrincipal user = new UserPrincipal(domain);
PrincipalSearcher pS = new PrincipalSearcher(user);

foreach (UserPrincipal result in pS.FindAll())
    {
    if (result != null && result.DisplayName != null)
        {
        DirectoryEntry entry = (DirectoryEntry)user.GetUnderlyingObject();
        IADsUser native = (IADsUser)entry.NativeObject;
        Console.WriteLine(result.DisplayName, native.PasswordExpirationDate);
        }
     }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

誰認得朕 2025-01-16 07:15:07

该异常意味着您正在对尚未保存的 UserPrincipal 对象调用 GetUnderlyingObject()

您正在为 PrincipalSearcher 创建作为过滤器的 user 对象调用 GetUnderlyingObject()。我认为您打算在结果上调用它:

DirectoryEntry entry = (DirectoryEntry)result.GetUnderlyingObject();

The exception means that you're calling GetUnderlyingObject() on a UserPrincipal object that hasn't been saved.

You're calling GetUnderlyingObject() on the user object that you created as the filter for your PrincipalSearcher. I think you intended to call it on result:

DirectoryEntry entry = (DirectoryEntry)result.GetUnderlyingObject();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文