This is the second post in my AD without Quest series. I am covering individual functions that can be combine to produce a wide variety of scripts. Today I am going to be covering how to connect to AD to read an object ADSPath. The ADSPath is basically the LDAP string to connect to that object. Once you have an object’s LDAP path it is very easy to work with the object.
When searching in AD all you need to do is use the directory searcher object and continue to narrow down the filter. There are some slight changes between searching for a user, computer and group, so I’ll cover each.
Param([STRING]$User)
$Searcher=New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter="(&(SamAccountName=$User)(objectcategory=user))"
$Searcher.PageSize = 1000
$Results=$Searcher.FindAll()
If(!$?){"AD searcher failed on $User"}
If ($Results.Count -eq 1){
$Results[0].properties.adspath
}Else{
Return $false
}
}
On the line with $Results[0].properties.adspath
it is important to note that the “adspath” portion is case sensitive. I really have no clue why that is the case. If you know, drop me a comment to help me out!
Param([STRING]$Computer)
$Searcher=New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter=”(&(CN=$Computer)(objectcategory=computer))”
$Searcher.PageSize = 1000
$Results=$Searcher.FindAll()
If(!$?){"AD searcher failed on $Computer"}
If ($Results.Count -eq 1){
$Results[0].properties.adspath
}Else{
Return $false
}
}
So as you can see, a couple of small changes will convert the function for use with computers instead of users. One final function converts this again for use with groups.
Param([STRING]$Group)
$Searcher=New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter=”(&(CN=$Group)(objectcategory=group))”
$Searcher.PageSize = 1000
$Results=$Searcher.FindAll()
If(!$?){"AD searcher failed on $Group"}
If ($Results.Count -eq 1){
$Results[0].properties.adspath
}Else{
Return $false
}
}
So there they are, but what can you do with them? There is a great variable type in PowerShell defined with the ADSI tag. Once a LDAP string is defined as and ADSI variable you can interact directly with that object by reading any property you want, and even changing them.
$UserLDAP.extensionAttribute1
>MyOldValue
$UserLDAP.Put(“extensionAttribute1”,”MyNewValue”)
$UserLDAP.SetInfo()
$UserLDAP.extensionAttribute1
>MyNewValue