5

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.

1
  • 1
    You can use a method from the URI class. [uri]::EscapeUriString('https://exmaple.com/string with spaces') Commented Nov 29, 2019 at 18:56

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.