May 16, 2007

escape apostrophe in ldap search filter in VBscript

It took me much time to figure out how to search a user whose name has "'"(apostrophe) inside. Basically you use another apostrophe to escape the apostrophe. Please see example:


Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = _
"SELECT distinguishedName FROM 'LDAP://dc=strongline,dc=home' WHERE objectCategory='user' AND cn ='D''Arcy, Who'"

REM ====>>>> use another apostrophe to escape one astrophe. It's hard to see the difference between two apostrophes and a double quote sign, please copy the code into an editor such as Notepad++ that can better show codes.

Set objRecordSet = objCommand.Execute