My Blog
My Blog
Finding a DSN from a SAMAccount Name
When doing automated/bulk AD administration using VBScript it’s not unusual to end up with a list of user targets by their SAMAccount name. While these are usable (using the GetOBject(“WinNT://<objectname>”) you don’t gain access to all of the user object attributes - you only get exposure to a limited set that were available in Windows NT.
Ideally, you want to connect to the user object using the LDAP designator (GetObject(“LDAP://<objectname>”) - to do this however you need the Distinguished Name (DSN) for the user object in question.
Now it’s pretty easy to export user objects to AD and find their DSN using such things a VLOOKUP in Excel, however sometimes it’s just easier to do it in the code - that’s what I tend to do anyway. That way you can re-use the code easily without having to re-do any of the groundwork to find the DSNs again from the SAMAccount.
I thought I’d share a small snippet of code I’ve done that will do this work for you. You can download my example piece of code here.
Let’s look at it.
========================================================
'Locate DSN from SAM Account Name
'Mark Coughlan
'12 June 2009
'Email: Mac@MarkC.me.uk
DIM NetBIOSDomain, Userpath
'Replace MarkC with the username you want to retrieve
GetDSN("MarkC")
wscript.echo "Netbios Domain: "&NetBIOSDomain&VBLF&"DSN: "&Userpath
wscript.quit
Private Function GetDSN(Username)
Dim oRoot, DNSDomain
SET oRoot=GetObject("LDAP://RootDSE")
DNSDomain = oRoot.Get("DefaultNamingContext")
' Use the NameTranslate object to find the NetBIOS
' domain name from the DNS domain name.
DIM oTrans
SET oTrans = CreateObject("NameTranslate")
oTrans.Init 3,DNSDomain
oTrans.Set 1,DNSDomain
NetBIOSDomain = oTrans.Get(3)
' Use NameTranslate to convert the NT user name to the
' DistinguishedName required for the LDAP provider.
oTrans.Init 1, Left(NetBIOSDomain, Len(NetBIOSDomain) - 1)
oTrans.Set 3, NetBIOSDomain & Username
UserPath = oTrans.Get(1)
End Function
========================================================
The actual code to get the DSN is in the private function ‘GetDSN’ so you can add this to your own code. Make sure you define the variables NetBIOSDomain & Userpath in your main code otherwise the private function won’t return any values as the variables will be private to that function!
Anyways, thought you may find that useful.
Friday, 12 June 2009
Email me about this article here.