Skip to content

Replace with evaluation function in PowerShell

June 29, 2012

I was looking for a way to convert a URL into a file name and back.  The problem is, of course, that URL contains characters that are not allowed in a file name such as forward slash (/), column (:), and question mark (?)

Of course, I found a whole bunch of solutions on the web, but I was not fully satisfied with any of them mostly because they were  hard to read and/or understand.

The solution that I created is short and sweet.  To convert the URL to a file name use:

get-SPSite http://mysharepoint/site

$name = [Regex]::Replace($site.Url, (\W), $toHex)

that replaces all non-alphanueric characters using the an anonymous evaluation function.

$toHex = {param($Match)(“%{0:x2}“) -f [int][char] $Match.Groups[1].Value}

the function uses -f (format) to convert each character with a % sign and the two-digit Hex value of the charachter.

ex:  http://place/my.%20weird-site-_name withspace/

becomes: http%3a%sf%2fplace%2fmy%2e%2520weird%2dsite%2d_name%20withspace%2f

The reverse function can be also used to decode URL parameters

$fromHex = {param($Match) [char][Convert]::ToInt32($Match.Groups[1].Value, 16)}

$url = [Regex]::Replace($name, ‘%(\w{2})’, $fromHex)

the regular expression “Replace” function finds the %xx combination in the string and replaces each one using the  anonymous function stored in $fromHex variable.  The evaluation function simply returns the ascii character of each Hexadecimal value.

Cool.  Isn’t it?



From → PowerShell

Leave a Comment

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: