71

I'm creating a PowerShell script that will assemble an HTTP path from user input. The output has to convert any spaces in the user input to the product specific codes, "%2F".

Here's a sample of the source and the output:

The site URL can be a constant, though a variable would be a better approach for reuse, as used in the program is: /http:%2F%2SPServer/Projects/"

$Company="Company"
$Product="Product"
$Project="The new project"
$SitePath="$SiteUrl/$Company/$Product/$Project"

As output I need:

'/http:%2F%2FSPServer%2FProjects%2FCompany%2FProductF2FThe%2Fnew%2Fproject'

4 Answers 4

111

To replace " " with %20 and / with %2F and so on, do the following:

[uri]::EscapeDataString($SitePath)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, this one worked. @Eric J's suggestion would work, but I'd have ahd to find the System.Web first. Your solution was simpler and it worked. Thanks
And, the reverse operation is [uri]::UnescapeDataString.
The question specifically asked how to convert space chars. Not other characters. So this answer is misleading as it will convert other chars as well.
@MarkWorrall While he said space, he showed slashes. Through context and examples, we can see he wishes to escape both slashes and spaces. Also through the context of his question, it appears he wishes to urlencode or escape the string for his use case.
It's also worth noting @MarkWorrall that more than just the question-asker visit these answers, and manojlds is conscious of that. If it really is not what the asker wants specifically then it's exactly why we have ticks and upvotes separately
71

The solution of @manojlds converts all odd characters in the supplied string. If you want to do escaping for URLs only, use

[uri]::EscapeUriString($SitePath)

This will leave, e.g., slashes (/) or equal signs (=) as they are.

Example:

# Returns http%3A%2F%2Ftest.com%3Ftest%3Dmy%20value
[uri]::EscapeDataString("http://test.com?test=my value")

# Returns http://test.com?test=my%20value
[uri]::EscapeUriString("http://test.com?test=my value") 

4 Comments

If you want to preserve slashes, you should escape the query parameters before appending them to the URL. (What if a query parameter includes a slash or equals sign?) There's no way to tell which slashes should be preserved, and which should not.
For others that come to find this and to be clear on the differences between the two methods. EscapeDataString is for escaping query string values, it will escape all url path and special characters. Ex the 'my value' part of the example Uri provided above. EscapeUriString is for escaping Uri path segments, it will prepare the string to be used in a Uri path. Ex the 'my path/to/success' in example.com/my path/to/success?test=my/value&user1=dom\username&user2=username@dom will become my example.com/my%20path/to/success?test=my%2Fvalue&user=dom%5Cusername&username%40dom
And, the reverse operation for both of them is [uri]::UnescapeDataString
Thanks! I added a couple functions to my repertoire. function URLEncode-QueryParam($queryParam) { return [uri]::EscapeDataString($queryParam) } function URLEncode-URI($uri) { return [uri]::EscapeUriString($uri) }
21

For newer operating systems, the command is changed. I had problems with this in Server 2012 R2 and Windows 10.

[System.Net.WebUtility] is what you should use if you get errors that [System.Web.HttpUtility] is not there.

$Escaped = [System.Net.WebUtility]::UrlEncode($SitePath)

2 Comments

I assume this is a comment on Eric J's answer.
It has nothing to do with the operating system version, but rather what version of the framework you have installed.
16

The output transformation you need (spaces to %20, forward slashes to %2F) is called URL encoding. It replaces (escapes) characters that have a special meaning when part of a URL with their hex equivalent preceded by a % sign.

You can use .NET framework classes from within Powershell.

[System.Web.HttpUtility]::UrlEncode($SitePath) 

Encodes a URL string. These method overloads can be used to encode the entire URL, including query-string values.

http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx

7 Comments

this gives + instead %20, so use the one beneath
@edelwater; + is a valid encoding of the space character in a URL. I'm pretty sure the OP just needs a validly encoded URL, not specifically %20 for space.
never run urlencode, always run uri:escapedatastring (and always run urldecode); google / stackoverflow it eg blogs.msdn.com/b/yangxind/archive/2006/11/09/…
When I tried it I got Unable to find type [System.Web.HttpUtility]: make sure that the assembly containing this type is loaded. At line:1 char:25 + [System.Web.HttpUtility] <<<< ::UrlEncode("Peter") + CategoryInfo : InvalidOperation: (System.Web.HttpUtility:String) [], RuntimeException + FullyQualifiedErrorId : TypeNotFound. Would this be related to the .NET version?
@PeterMortensen Add-Type -AssemblyName System.Web
|

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.