Escaping Strings in URLs

by Jan 10, 2022

When adding string information to URLs, i.e. to construct requests for calling REST web services, it is important to escape special characters. The type [Uri] comes with methods to escape and unescaped string for use in URLs:

$Text = 'SOS Save me please!'
$Escaped = [Uri]::EscapeUriString($Text)

The result looks like this:


Now you can safely send the escaped string data to RESTful webservices, for example. This convers the text to morse code:

$Text = 'SOS Save me please!'
$url = "$Text"

$Escaped = [Uri]::EscapeUriString($url)

$result = Invoke-RestMethod -Uri $url

The result looks like this now:

... --- ...     ... .- ...- .     -- .     .--. .-.. . .- ... . ---.

Occasionally, escaping strings with this method can corrupt certain query strings. To work around this, check out tomorrow’s tips.

Twitter This Tip! ReTweet this Tip!