Converting VBScript's Escape Function

Definition: Encodes a string so it contains only ASCII characters.

Escape

Admittedly, this is another one of those functions you probably don’t use on a daily basis. To quote from the VBScript Language reference:

“The Escape function returns a string (in Unicode format) that contains the contents of charString. All spaces, punctuation, accented characters, and other non-ASCII characters are replaced with **%**xx encoding, where xx is equivalent to the hexadecimal number representing the character. Unicode characters that have a value greater than 255 are stored using the %uxxxx format.”

Hey, why not?

Shockingly, Windows PowerShell doesn’t include a built-in method for encoding a string in this fashion. However, you can easily do this by loading the .NET Framework System.Web class and then using the Web.Utility class’ URLEncode method. In other words, by executing a pair of commands similar to this:

[Reflection.Assembly]::LoadWithPartialName("System.Web")
$a = [web.httputility]::urlencode("https://www.microsoft.com/technet/scriptcenter/default.mspx")

When you run this command and then echo back the value of $a you should get the following:

http%3a%2f%2fwww.microsoft.com%2ftechnet%2fscriptcenter%2fdefault.mspx

And yes, that’s what it’s supposed to look like.

Return to the VBScript to Windows PowerShell home page