How To Extract Active Directory Users From Specific OU From DC Using Secure Port 636 (Via ADSI)?

Hello,

The following code will connect to our Domain Controller SERVERDC1 via TCP port 636 and extract the members of the group AppXYZ_AccessGroup.

I want to change this to extract the same user information, but for the entire OU OU=Users,DC=moh,dc=contoso,dc=com not just a specific group. Does anyone know how to edit this code to achieve this?

Thanks
Stuart

#Import the members of the Active Directory group "AppXYZ_AccessGroup"
([adsi]"LDAP://SERVERDC1:636/CN=AppXYZ_AccessGroup,OU=Applications,OU=Groups,DC=moh,dc=contoso,dc=com").member |
    ForEach-Object {[adsi]"LDAP://$_"} |
    select @{L="objectGUID";E={[guid]::New($_.objectGuid[0]).Guid}}, @{L="mail";E={$_.mail}}, @{L="givenName";E={$_.givenName}}, @{L="sn";E={$_.sn}}, @{L="manager1";E={$_.manager1}}, @{L="sAMAccountName";E={$_.sAMAccountName}}, @{L="department";E={$_.department}}, @{L="physicalDeliveryOfficeName";E={$_.physicalDeliveryOfficeName}}, @{L="friendlyNames";E={$_.friendlyNames[0]}}, @{L="useraccountcontrol";E={$_.useraccountcontrol}}, @{L="objectclass";E={$_.objectclass}}, @{L="AccountExpirationDate";E={$_.AccountExpirationDate}} |
    Export-Csv "C:\Temp\LDAPExtract.csv" -NoTypeInformation

There are many guides on using ADSI with Powershell:

Working with Active Directory using PowerShell ADSI adapter - TechNet Articles - United States (English) - TechNet Wiki (microsoft.com)

If you want to connect to a specific DC on a specific port, you just need to append that to the LDAP path in examples.

It appears that AccountExpirationDate is not an available property using this method, but I can use accountexpires as a filter instead (not ideal, but will be okay for my purpose). FYI without -Stream the Out-String adds a new line each time (using PSVersion 5.1.18362.1593)

$Root = [adsi]"LDAP://SERVERDC1:636/OU=Users,DC=moh,dc=contoso,dc=com"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher($Root)
$Searcher.filter = "(objectClass=user)"
$Results = @()

$allObjects = $Searcher.FindOne()
foreach ($obj in $allObjects)
{
 $Object = New-Object PSObject -Property @{
    objectGUID=([guid]::New(($obj.Properties).objectguid[0]).Guid);
    mail=(($obj.Properties).mail|Out-String -Stream);
    sn=(($obj.Properties).sn|Out-String -Stream);
    manager1=(($obj.Properties).manager1|Out-String -Stream);
    sAMAccountName=(($obj.Properties).samaccountname|Out-String -Stream);
    department=(($obj.Properties).department|Out-String -Stream);
    physicalDeliveryOfficeName=(($obj.Properties).physicaldeliveryofficename|Out-String -Stream);
    friendlyNames=(($obj.Properties).friendlynames[0]|Out-String -Stream);
    useraccountcontrol=(($obj.Properties).useraccountcontrol|Out-String -Stream);
    AccountExpires=(($obj.Properties).accountexpires|Out-String -Stream);
 }
 $Results=$Object
 }
  
$Results | Export-Csv "C:\Temp\LDAPExtract.csv" -NoTypeInformation