From this post I learned that I can use [Regex]::Escape() to escape all the commonly escaped characters in string variables. The problem is that I'm going to use a path that contains & characters and then use that in a URL for a RestAPI call, and that escape method does not escape the & character.
When the path contains & the API interprets this as an operator in the URL and is not parsed correctly:
$MyPath = "\\Server\Share\Something & Something Else"
$MyURL= "http://localhost/Address/to/APIResource/"
Invoke-RestMethod -Method Get -Uri ("$MyURL" + "?path=$MyPath") -UseDefaultCredentials
The ?path=$MyPath is the problem, since $MyPath contains & and will therefore not work. How can I escape the & character inside $MyPath to make it work with the RestAPI?
I learned that I can use
[Regex]::Escape()to escape all the commonly escaped characters in string variables
And now you'll learn that that isn't true at all :)
[regex]::Escape() only escapes characters that would otherwise risk being interpreted as escape sequences as defined by .NET's regular expression grammar - it's designed for, and only guaranteed to work in, that context.
For URI parameters, you'll want to use [uri]::EscapeDataString():
Invoke-RestMethod -Uri ("$MyURL" + [uri]::EscapeDataString("?path=$MyPath")) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With