LDAP Query based on account SID in VBscript

This is a bit of code I wish I’d found sooner. There is a – it seems mostly undocumented – feature of the ldap provider in Server 2003 that allows you to form an ldap query just on the SID of an account:

bindSid = "LDAP://<sid =" & SID & ">"
set oVal = GetObject(bindSid)
Result = oVal.Get("cn")
set oVal = Nothing

So if you have a list of SIDs and want to translate them into meaningful account names, this will do it without relying on using WMI – which on a lot of secure networks is locked down (or at least should be!).

Why do I need this? It’s a part of a larger script I’m writing that will archive specific Group Policy Objects from the \SYSVOL\<domainname>\Policies\ folder of a PDCe. One of the files in a GPO is the GptTmpl.inf file which gives a list of the User Rights Assignments (SeBackupPrivilege, SeShutdownPrivileg etc) along with the SIDs of the accounts that have been given those privileges (e.g. S-1-5-19). I wrote a script that reads the SIDs and queries the DC for the account names. This code fragment works more reliably (and I think faster) than the WMI calls I was previously using.