簡體   English   中英

如何使用WMI獲取計算機的當前OU並列出該OU中的所有其他計算機?

[英]How do I use WMI to get the current OU of a computer and list all other computers in that OU?

我正在使用WMI,我正在嘗試找到一個powershell腳本,它允許我獲取本地計算機的OU,然后獲取該OU中的完整計算機列表。

干得好:

$ComputerName = '<Name of Computer>';
$Computer = Get-WmiObject -Namespace 'root\directory\ldap' -Query "Select DS_distinguishedName from DS_computer where DS_cn = '$ComputerName'";
$OU = $Computer.DS_distinguishedName.Substring($Computer.DS_distinguishedName.IndexOf('OU='));
$ComputersInOU = Get-WmiObject -Namespace 'root\directory\ldap' -Query "Select DS_cn, DS_distinguishedName from DS_computer where DS_distinguishedName like '%$OU'";

我認為這也可以在子OU中找到計算機,但我不知道如何在不進行大量查詢的情況下將其限制為單個OU。 查詢語法相當稀疏。 在檢索完整列表之后消除子OU對象可能是執行任何表現的唯一方法。

公平警告:這很慢。 真的很慢。 就像“哦,垃圾,我打破了什么?!” 慢。 我把它指向一台與少於20台其他計算機共享OU的計算機,運行起來需要將近一分鍾。 即使是第一次只讀取一台計算機也需要1秒鍾以上。

這是我建議的:

$ComputerName = '<Name of Computer>';
Import-Module -Name ActiveDirectory -Cmdlet Get-ADComputer, Get-ADOrganizationalUnit;
$Computer = Get-ADComputer $ComputerName;
$OU = $Computer.DistinguishedName.SubString($Computer.DistinguishedName.IndexOf('OU='));
$ComputersInOU = Get-ADComputer -Filter * -SearchScope OneLevel -SearchBase (Get-ADOrganizationalUnit $OU).DistinguishedName;

這需要2秒,包括加載Active Directory模塊。 已經加載,這需要不到200毫秒。

如果您無權訪問ActiveDirectory PowerShell模塊,則可以使用[ADSISearcher] 由於結果如何呈現,這些也很難使用,但它們甚至比ActiveDirectory模塊更快,它基本上只是一個包裝器。

$ComputerName = '<Name of Computer>';
$ADSISearcher = New-Object System.DirectoryServices.DirectorySearcher;
$ADSISearcher.Filter = '(&(name=' + $ComputerName + ')(objectClass=computer))';
$ADSISearcher.SearchScope = 'Subtree';
$Computer = $ADSISearcher.FindAll();

$OU = $($Computer.Properties.Item('distinguishedName')).Substring($($Computer.Properties.Item('distinguishedName')).IndexOf('OU='));
$OUADsPath = 'LDAP://' + $OU;

$ADSISearcher = New-Object System.DirectoryServices.DirectorySearcher;
$ADSISearcher.Filter = '(objectClass=computer)';
$ADSISearcher.SearchScope = 'OneLevel';
$ADSISearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry($OUADsPath);
$ComputersInOU = $ADSISearcher.FindAll();

這運行大約50毫秒。

但是,請注意,如果ADSI系統未正確調用或者調用FindAll()並且結果從未使用過, 則已知ADSI系統包含內存泄漏 我自己用這種方法創建了對象然后沒有丟棄它們並且讓我的shell進程在一夜之間打開,當我第二天早上進入時,我的系統幾乎沒有響應,因為所有的內存都被消耗了。 ActiveDirectory模塊完全避免了這些問題,並且代碼更輕,所以除非你真的需要那些額外的幾毫秒而不是我喜歡的模塊。

暫無
暫無

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

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