如何处理嵌入HTA的VBScript函数中的特殊字符以避免AD用户查询报错?
Handling Special Characters in AD Display Names for HTA/VBScript
Great question! The issue you're encountering happens because special characters like /, #, or others that have meaning in HTML (such as <, >, or &) can break the HTML structure when directly injected into the innerHTML property. Here's a straightforward fix:
Step 1: Add an HTML Escape Function
Create a VBScript function to convert special characters into their safe HTML entity equivalents. This ensures the characters are displayed as plain text instead of being interpreted as part of the HTML code.
Step 2: Modify Your Existing Code
Apply the escape function to the user's name before inserting it into the innerHTML property.
Modified Full Code
<script language="vbscript"> Function EscapeHTML(str) If IsNull(str) Then EscapeHTML = "" Exit Function End If ' Replace HTML special characters with their safe entity equivalents str = Replace(str, "&", "&") str = Replace(str, "<", "<") str = Replace(str, ">", ">") str = Replace(str, """", """) str = Replace(str, "'", "'") str = Replace(str, "/", "/") str = Replace(str, "#", "#") EscapeHTML = str End Function Sub GetUserName() Set objSysInfo = CreateObject("ADSystemInfo") Set objCurrentUser = GetObject("LDAP://" & objSysInfo.UserName) Dim GetUser ' Combine givenName and lastName GetUser = objCurrentUser.givenName & " " & objCurrentUser.lastName ' Escape special characters before using in HTML GetUser = EscapeHTML(GetUser) ' Note: The original line `Set WshNetwork = Nothing` referenced an undefined variable — removed here since it wasn't used user.innerHTML = "<font color=""black"" face=""Verdana"" size=""4"">" & "Dear " & GetUser & ", Thank you" & "</font>" End Sub </script>
Key Notes
- The
EscapeHTMLfunction handles all common HTML special characters, not just/and#. This prevents future issues if a user's name contains characters like<or&, which would otherwise completely break the HTML layout. - If you only need to target
/and#specifically, you can simplify the function to only include those twoReplacelines, but full HTML escaping is the more robust approach. - I removed the
Set WshNetwork = Nothingline sinceWshNetworkwasn't defined or used in your original code — feel free to add backSet WshNetwork = CreateObject("WScript.Network")if you need it for other functionality.
内容的提问来源于stack exchange,提问作者user1111726




