3

What is the equivalent of Javascripts encodeURI() / encodURIComponent() in Powershell?

I'm encoding a URL (need some %20s in it) and I hate to do that manually.

leeand00
  • 25,510
  • 39
  • 140
  • 297

1 Answers1

8

You can utilize the System.Uri class for these cases.

The encodeURI() equivalent would be to either use the EscapeUriString static method from the class or cast your URI string as a System.URI type and access the AbsoluteUri property.

$uri = 'https://example.com/string with spaces'
# Method 1
[uri]::EscapeUriString($uri)
# Method 2
([uri]$uri).AbsoluteUri

# Output
https://example.com/string%20with%20spaces

The encodeURIComponent() equivalent can be done using the class's EscapeDataString method.

$uri = 'https://example.com/string with space&OtherThings=?'
[uri]::EscapeDataString($uri)

#Output

https%3A%2F%2Fexample.com%2Fstring%20with%20space%26OtherThings%3D%3F

Note: You do not have to define a variable ($uri in this case). You can just replace that with a quoted string. I only used the variable for readability purposes.

AdminOfThings
  • 23,946
  • 4
  • 17
  • 27