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) $Escaped
The result looks like this:
SOS%20Save%20me%20please!
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 = "https://api.funtranslations.com/translate/morse.json?text=$Text" $Escaped = [Uri]::EscapeUriString($url) $result = Invoke-RestMethod -Uri $url $result.contents.translated
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.