title: Only show Active Directory OU that contain User Accounts
body: <p>I can easily get a list of OU's from our Domain's AD but I only want to grab OU's with user accounts.</p>
  
  <p>I am currently grabbing the list of OU's, and then going through each one to get the list of users and the count but it can take about 30 seconds to process all of that data.</p>
  
  <p>I was hoping there was some quicker way to accomplish the same task.</p>
  
  <pre><code>Public Sub GetActiveDirectoryOuList()
      Dim de As DirectoryEntry = Nothing
      Dim ds As DirectorySearcher = Nothing
      Dim results As SearchResultCollection = Nothing
  
      Try
          de = New DirectoryEntry("LDAP://DC=csileasing,DC=com")
          ds = New DirectorySearcher(de, "(objectClass=organizationalUnit)")
          results = ds.FindAll
  
          If results.Count = 0 Then Exit Try
  
          For Each result As SearchResult In results
              Dim count As Integer = GetUserCountForOU(result.Properties("distinguishedName")(0).ToString)
              If count &gt; 0 Then
                  Dim ou As New OrgUnitInfo
                  ou.DistinguisedName = result.Properties("distinguishedName")(0).ToString
                  ou.Name = result.Properties("name")(0).ToString
                  ou.UsersCount = count
                  adOrgUnitList.Add(ou)
              End If
          Next
  
      Catch ex As Exception
          'MessageBox.Show(ex.Message)
      Finally
          If ds IsNot Nothing Then ds.Dispose()
          If de IsNot Nothing Then de.Dispose()
          If results IsNot Nothing Then results.Dispose()
      End Try
  
  End Sub
  </code></pre>