C# 如何使用c获取AD中计算机的objectguid和objectsid

C# 如何使用c获取AD中计算机的objectguid和objectsid,c#,C#,基于 我正在尝试获取ad域中计算机的objectGUID和objectSID 所以我补充说 mySearcher.PropertiesToLoad.Add("objectGUID"); mySearcher.PropertiesToLoad.Add("objectSID"); 并尝试通过以下方式接收信息: string computerGUID = (string)resEn

基于

我正在尝试获取ad域中计算机的objectGUID和objectSID

所以我补充说

                mySearcher.PropertiesToLoad.Add("objectGUID");
                mySearcher.PropertiesToLoad.Add("objectSID");
并尝试通过以下方式接收信息:

                            string computerGUID = (string)resEnt.Properties["objectGUID"][0].ToString();
                            string computerSID = (string)resEnt.Properties["objectSID"][0].ToString();
但只需要返回“System.Byte[]”。我怎样才能得到真实的数据


谢谢

您可以通过从C运行以下PowerShell命令来完成此操作:


获取用户用户名-属性*|选择SamaccountName、ObjectSid、ObjectGUID

应用筛选器后,使用FindOne根据筛选器检索第一个条目

mySearcher.PropertiesToLoad.Add("objectGUID");
mySearcher.PropertiesToLoad.Add("objectSID");
SearchResult searchResult = mySearcher.FindOne(); //FindAll() can return a collection

var objectGUID = searchResult.GetDirectoryEntry().Properties["objectGUID"].Value;

var computerGUID = searchResult.GetDirectoryEntry().Properties["objectSID"].Value;

GetSidString是非托管代码的一部分,因此您必须p/Invoke

注:

第二种方法强调objectSid,您必须为objectGUID相应地修改它

参考资料:


请注意,在使用ToString时不需要强制转换字符串;看起来您得到的是一个字节数组。您可以尝试使用字符串computerGUID=Encoding.UTF8.GetStringRecent.Properties[objectGUID][0],0,Recent.Properties[objectGUID][0]。lengthLook:这是给用户的,但逻辑是一样的。我需要ad计算机的属性,我不能使用powershell,因为我用c编写了一个应用程序

 mySearcher.PropertiesToLoad.Add("objectGUID");
 mySearcher.PropertiesToLoad.Add("objectSID");

 SearchResultCollection results;

 results = mySearcher.FindAll();

string sidStringValue="";
string guidStringValue="";

    foreach (var result in results)
    {

                  //reset SID

                  byte[] SID = null;

                  if (result.Properties[“objectSid”].Count > 0)

                  {

                      SID = (byte[]) result.Properties[“objectSid”][0];

                  }

                  sidStringValue = GetSidString(SID); 

             }//


[DllImport(“advapi32”, CharSet = CharSet.Auto, SetLastError = true)]

static extern bool ConvertSidToStringSid([MarshalAs(UnmanagedType.LPArray)] byte[] pSID, out IntPtr ptrSid);


public static string GetSidString(byte[] sid)
{

            IntPtr ptrSid;

            string sidString;

            if (!ConvertSidToStringSid(sid, out ptrSid))

                throw new System.ComponentModel.Win32Exception();

            try

            {

                sidString = Marshal.PtrToStringAuto(ptrSid);

            }

            finally

            {

                Marshal.FreeHGlobal(ptrSid);

            }

            return sidString;

}