simple ad from powershell

a nice post from Norman Drews on two approaches to AD access from Powershell

Option one is to use the AD module provided by Microsoft. You can see if  you have it with

get-module -listavailable

FYI i mistyped that since i wanted to get ALL modules so tried with get-modules.  Powershell police set the speed limit at one – so it is module, not modules.  Might only return one – or none.  If you don’t see ActiveDirectory, then the following will not work:

import-module ActiveDirectory.

There are two approaches, GET the module (RSAT package or install ActiveDirectory role – you ARE a server, correctly?) or use the trick that Don Jones showed at WindowsITPro where you start a session with a controller, and import session to get the library loaded on your local machine.

$s = new-pssession -computername "AD-server"

# in that session, load the AD module
Invoke-Command -session $s -script { Import-Module ActiveDirectory }

#now import that session into your local session.  
# Jones suggests you provide a prefix as a namespace
Import-PSSession -session $s -module ActiveDirectory -prefix Rem

#run commands in the local session as if the module was local
Get-RemADUser -filter * -searchbase "ou=users,dc=university,dc=edu"

#close the session when you are done and access to the module goes away
$s | Remove-PSSession

HOWEVER, you can also use the .NET libraries, which will be on your machine assuming the appropriate frameworks are loaded.

$s = New-Object -TypeName System.DirectoryServices.DirectorySearcher
$s.SearchRoot = [adsi]$root
$s.SearchScope = $scope
$s.Filter = $LDAPFilter

where $root (= “LDAP://ou=MyTestOU,dc=university,dc=edu”) , $scope (=”subtree”) and $filter (=”(&(objectcategory=User))”) are appropriately set.

Do a find all, get the getDirectoryEntry for each item, and go from there

$result = $s.FindAll()
# Enumerate through all matches
foreach ($item in $result)
{
 $entry = $item.GetDirectoryEntry()
# more here
}

This is about as succinct as it gets.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.