Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell, escaping specific character in string variable not present in regex escape method

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?

like image 452
Tanaka Saito Avatar asked Nov 06 '25 13:11

Tanaka Saito


1 Answers

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")) ...
like image 176
Mathias R. Jessen Avatar answered Nov 09 '25 09:11

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!