Tuesday, April 14, 2009

Domain LDAP RootDSE with Fries and a Shake

How many times have you seen a script that pulls something from Active Directory, but it has the LDAP domain suffix hard-coded? I'm talking about "dc=contoso,dc=com" and so on. It's just dumb. Don't do that! Stop! Put down the keyboard and back away with your beer in the air. There's a better way, and it's actually EASIER. Imagine that. I actually used it in a previous script post for inventorying (say that ten times, fast) so it's not really new here. You'll find this in many other places as well, posted long before me, probably dating back to the prehistoric Ldapian era when X500 dinosaurs ruled the Earth. I told you, I'm feeling real stupid right now.

'----------------------------------------------------------------
' comment: obtain object handle to RootDSE of domain
'----------------------------------------------------------------

Set objRootDSE = GetObject("LDAP://rootDSE")

'----------------------------------------------------------------
' comment: query for LDAP domain DN (eg. DC=domain,DC=com)
'----------------------------------------------------------------

LDAP_DN = Domain_LDAP()
ADSI_DN = Domain_NetBIOS(LDAP_DN)

'----------------------------------------------------------------

Function Domain_LDAP()
Domain_LDAP = objRootDSE.Get("defaultNamingContext")
End Function

'----------------------------------------------------------------

Function Domain_NetBIOS(ldapdn)
Domain_NetBIOS = Replace(Replace(ldapdn,"DC=",""),",",".")
End Function


So, anywhere in your vast array of VBscript files where you're querying Active Directory for information, and you have the LDAP string hard-coded, just replace it with the junk above and your code is instantly portable! Instantly! Just add hot water and stir. Makes its own sauce.

1 comment:

skatterbrainz said...

I had to edit this post to correct a small glitch in the code. The line that sets objRootDSE requires enclosing double-quotes as well as removing the trailing forward-slash. So GetObject(ldap://rootDSE/) should have been GetObject("LDAP://rootDSE") Sorry if that caused anyone some angst.