我有一个用户帐户的SID,我想要它所属的组的SID

JCC*_*CyC 7 c# wmi wql

这必须从远程机器获得.以下查询不适用于SID,但适用于组和帐户名称.

"SELECT GroupComponent FROM Win32_GroupUser WHERE PartComponent = \"Win32_UserAccount.Domain='" + accountDomain + "',Name='" + accountName + "'\""
Run Code Online (Sandbox Code Playgroud)

它返回的Win32_Group对象以字符串的形式出现,它们只有域名和名称(即使Win32_Group具有SID属性).

我有这种下沉的感觉,我将不得不:

  1. 通过查询Win32_SID将SID转换为帐户名称;
  2. 执行上面的查询;
  3. 通过查询Win32_Group 将每个结果组名称转换为SID.

tva*_*son 3

您可以使用System.DirectoryServices.AccountManagement命名空间类吗?

using (var context = new PrincipalContext( ContextType.Domain ))
{
    using (var user = UserPrincipal.FindByIdentity( context, accountName ))
    {
        var groups = user.GetAuthorizationGroups();
        ...iterate through groups and find SIDs for each one
    }
}
Run Code Online (Sandbox Code Playgroud)

它应该与 ContextType.Machine 一起使用,尽管您需要指定计算机名称并具有适当的权限。

using (var context = new PrincipalContext( ContextType.Machine,
                                           "MyComputer",
                                           userid,
                                           password ))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

有一篇不错的 MSDN文章(虽然有点长)介绍了如何使用新的 .NET 3.5 帐户管理命名空间。