RSS

VBScript: Adding strings with comma into keys causes “The key is already associated…” error

04 May

These past few days as I am furiously pounding the keyboard trying to re-engineer someone else script using dictionary, I came across an expected problem:

I had an LDAP query against an OU to grab all user objects in that OU. As you know, depending on how your organize your AD OU, the DN of the user object usual looks like this (for example) “CN=Wong,\ Kelvin,OU=Users,OU=SGP,DC=MYCO,DC=COM”

So I have an array of DNs and want to use that to create a dictionary. So I did the followng:

Set d = CreateObject("Scripting.Dictionary")
for i=0 to ubound(arrDN)-1
  d.add arrDN(i), "X"
Next

When this ran, it threw out “The key is already associated…” error. At first I thought I had duplicated DNs in the OU, but that is impossible in AD.

It turns out that the keys never got added because each comma in the DN string becomes a delimiter and nothing was added, plus the error was generated. It took me a while to figure this out because I was passing the  key string as a variable and did not expect it will interpret the commas.

So the proper way to create a dictionary if your key strings contains commas is close them with single or double quotes:

Set d = CreateObject("Scripting.Dictionary")
for i=0 to ubound(arrDN)-1
  d.add """" & arrDN(i) & """" , "X"
Next

Now the issue here is that if you want to reference an item using the key or the key itself, you will need to add the quotes into your string also. For example

s = "CN=Wong,\ Kelvin,OU=Users,OU=SGP,DC=MYCO,DC=COM"
if d.Exists("""" & s & """") then wscript.echo "Found it!"
Advertisements
 
Leave a comment

Posted by on May 4, 2012 in Scripts, VBScripts

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: