|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.DirectoryServices; |
| 4 | +using System.Runtime.InteropServices; |
| 5 | + |
| 6 | +namespace NETworkManager.Utilities.ActiveDirectory; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Queries Active Directory for computer accounts under a search base, including subtrees. |
| 10 | +/// Uses the current Windows identity to bind to the directory. |
| 11 | +/// </summary> |
| 12 | +public static class ActiveDirectoryComputerSearcher |
| 13 | +{ |
| 14 | + private const int LdapPageSize = 500; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Returns computer accounts under <paramref name="ldapSearchRoot"/> with subtree scope. |
| 18 | + /// </summary> |
| 19 | + /// <param name="ldapSearchRoot">Distinguished name or LDAP path (with or without LDAP:// prefix).</param> |
| 20 | + /// <param name="excludeDisabledComputerAccounts">When true, computer accounts with ACCOUNTDISABLE are omitted.</param> |
| 21 | + /// <returns>Sorted list by profile name.</returns> |
| 22 | + /// <exception cref="ArgumentException">When <paramref name="ldapSearchRoot"/> is null or whitespace.</exception> |
| 23 | + /// <exception cref="InvalidOperationException">When the directory search fails.</exception> |
| 24 | + public static IReadOnlyList<ActiveDirectoryComputerRecord> GetComputersInSubtree( |
| 25 | + string ldapSearchRoot, |
| 26 | + bool excludeDisabledComputerAccounts) |
| 27 | + { |
| 28 | + ArgumentException.ThrowIfNullOrWhiteSpace(ldapSearchRoot); |
| 29 | + |
| 30 | + var ldapPath = NormalizeLdapPath(ldapSearchRoot.Trim()); |
| 31 | + |
| 32 | + var ldapFilter = excludeDisabledComputerAccounts |
| 33 | + ? "(&(&(objectCategory=computer)(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" |
| 34 | + : "(&(objectCategory=computer)(objectClass=computer))"; |
| 35 | + |
| 36 | + try |
| 37 | + { |
| 38 | + using var directoryEntry = new DirectoryEntry(ldapPath); |
| 39 | + using var directorySearcher = new DirectorySearcher(directoryEntry) |
| 40 | + { |
| 41 | + SearchScope = SearchScope.Subtree, |
| 42 | + Filter = ldapFilter, |
| 43 | + PageSize = LdapPageSize, |
| 44 | + Tombstone = false |
| 45 | + }; |
| 46 | + |
| 47 | + directorySearcher.PropertiesToLoad.Add("dnsHostName"); |
| 48 | + directorySearcher.PropertiesToLoad.Add("name"); |
| 49 | + directorySearcher.PropertiesToLoad.Add("sAMAccountName"); |
| 50 | + |
| 51 | + var computers = new List<ActiveDirectoryComputerRecord>(); |
| 52 | + |
| 53 | + using var searchResults = directorySearcher.FindAll(); |
| 54 | + foreach (SearchResult searchResult in searchResults) |
| 55 | + { |
| 56 | + var dnsHostName = GetFirstPropertyString(searchResult, "dnsHostName"); |
| 57 | + var nameAttribute = GetFirstPropertyString(searchResult, "name"); |
| 58 | + var samAccountName = GetFirstPropertyString(searchResult, "sAMAccountName"); |
| 59 | + |
| 60 | + var profileName = !string.IsNullOrEmpty(samAccountName) |
| 61 | + ? samAccountName.TrimEnd('$') |
| 62 | + : nameAttribute; |
| 63 | + |
| 64 | + if (string.IsNullOrWhiteSpace(profileName)) |
| 65 | + profileName = nameAttribute; |
| 66 | + |
| 67 | + if (string.IsNullOrWhiteSpace(profileName)) |
| 68 | + continue; |
| 69 | + |
| 70 | + computers.Add(new ActiveDirectoryComputerRecord(profileName.Trim(), dnsHostName ?? string.Empty)); |
| 71 | + } |
| 72 | + |
| 73 | + computers.Sort((left, right) => |
| 74 | + string.Compare(left.ProfileName, right.ProfileName, StringComparison.OrdinalIgnoreCase)); |
| 75 | + |
| 76 | + return computers; |
| 77 | + } |
| 78 | + catch (COMException exception) |
| 79 | + { |
| 80 | + throw new InvalidOperationException( |
| 81 | + "Active Directory search failed. Verify the search base, permissions, and domain connectivity.", |
| 82 | + exception); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + private static string NormalizeLdapPath(string input) |
| 87 | + { |
| 88 | + if (input.StartsWith("LDAP://", StringComparison.OrdinalIgnoreCase) || |
| 89 | + input.StartsWith("LDAPS://", StringComparison.OrdinalIgnoreCase) || |
| 90 | + input.StartsWith("GC://", StringComparison.OrdinalIgnoreCase)) |
| 91 | + return input; |
| 92 | + |
| 93 | + return "LDAP://" + input; |
| 94 | + } |
| 95 | + |
| 96 | + private static string GetFirstPropertyString(SearchResult searchResult, string propertyName) |
| 97 | + { |
| 98 | + if (!searchResult.Properties.Contains(propertyName) || searchResult.Properties[propertyName].Count == 0) |
| 99 | + return string.Empty; |
| 100 | + |
| 101 | + return searchResult.Properties[propertyName][0]?.ToString() ?? string.Empty; |
| 102 | + } |
| 103 | +} |
0 commit comments