簡體   English   中英

c#如何獲取AD中Computer的objectguid和objectid

[英]How to get the objectguid and objectsid of Computer in AD using c#

基於列出活動目錄中的所有計算機

我正在嘗試獲取我的廣告域中計算機的 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 命令來執行此操作:

Get-ADUser USERNAME -Properties * | 選擇 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;

或者


 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); 

             }//

GetSidString 是非托管代碼的一部分,因此您必須 P/Invoke


[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;

}

注意

第二種方法強調objectSid您必須為objectGUID相應地修改它

參考:

https://philippsen.wordpress.com/2010/12/07/retrieving-user-sid-using-directoryentry-and-directorysearcher/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM