Two Methods for Accessing AD Info from Powershell
There are two basic methods for accessing Active Directory information from within Powershell scripts: using Active Directory Service Interfaces (ADSI), and the Powershell ActiveDirectory module.
This article is about ADSI.
ADSI is the method I'm using below. There are two basic ADSI tools used with this method: [adsi] is an accelerator (or "alias") to System.DirectoryServices.DirectoryEntry, which points to actual objects within AD, and [adsisearcher] is an accelerator to System.DirectoryServices.DirectorySearcher, which is used for searching through AD.
Using the ADSI Method for accessing information in Active Directory
Suppose you want to search, from within Powershell, for data in Active Directory on a Windows PC that is not bound to a domain, but is on the same network as a domain server.
You'll need to tell the Searcher what domain credentials to use.
To do this:
# Prompt user for creds; store them in $creds.UserName and $creds.Password
$creds = Get-Credential
# Specify the domain we want to search.
$DomainName = "LDAP://mydomain.com/DC=mydomain,DC=com"
# Create a directory-entry object to that domain, with appropriate creds.
$DirEntry = New-Object `
-TypeName System.DirectoryServices.DirectoryEntry `
ArgumentList $DomainName,
$creds.UserName,
$($creds.GetNetworkCredential().Password)
We now have the Directory Entry object that points to the root of the Active Directory tree, along with the credentials needed for accessing that root.
Now we're ready to build our Searcher, and then to run it.
$Searcher = New-Object -type System.DirectoryServices.DirectorySearcher
Notice the similarity in types between the Searcher object and the Directory Entry object. That's the difference between [adsi] and [adsisearcher] you might see elsewhere.
Now we'll plug our Directory Entry object into the Searcher object:
$Searcher.SearchRoot = $DirEntry
And now we'll do our search (not limiting it in any way; expect a deluge of info).
$Searcher.FindAll()
Splooge!
No comments:
Post a Comment