PowerShell Active Directory Interaction Without Using Active Directory Modules

I recently had the requirement to interact with Active Directory using PowerShell but without using the *AD* cmdlets from the ActiveDirectory PowerShell module. The reason being the script would be running from a server that won’t meet the requirements to install the module and it was running Powershell V2. In this post I’ll be looking at two alternatives to achieve PowerShell Active Directory interaction without using Active Directory modules. Just to reiterate the easiest way to interact with Active Directory from PowerShell is the Active Directory module, link here. But if you can’t these alternatives will come in handy.

 

Find an object example:

$domain = New-Object DirectoryServices.DirectoryEntry
 $search = [System.DirectoryServices.DirectorySearcher]$domain
 $search.Filter = "(&(objectClass=user)(sAMAccountname=UserToLookFor))"
 $user = $search.FindOne().GetDirectoryEntry()

When it comes to creating objects you can create generic Directory entries and populate their Active Directory attributes directly but that would require knowledge of the attributes before hand.

$objDomain = New-Object System.DirectoryServices.DirectoryEntry 
$obj = $objDomain.Create("$name""CN=ContainerName"$obj.Put("AttributeName","AttributeValue")
$obj.CommitChanges()

Or if you are on .Net 3.5 or higher you can use classes from the System.DirectoryServices.AccountManagement namespace to create typed objects.

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ctx = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$obj = New-Object System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $ctx
$obj.Name = "test"
$obj.Save()
  • Using Active Directory Service Interface ADSI. I mostly used the Exists static method on the ADSI class to check if objects exist in Active Directory.
    [adsi]::Exists("LDAP://OU=test,DC=domain,DC=com")

    You can also use the ADSI PowerShell adapter to manipulate objects, there are a few examples here on TechNet. I found the classes from the ActiveDirectory namespace easier to use when it comes to manipulating objects but the Exists method works well if you already have the Distinguished Name of an object.

Francois Delport