Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace spaces with %20 in PowerShell?

Tags:

powershell

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' 
like image 370
Barry Cohen Avatar asked May 08 '14 17:05

Barry Cohen


People also ask

How do I remove spaces from output in PowerShell?

PowerShell Trim() methods (Trim(), TrimStart() and TrimEnd()) are used to remove the leading and trailing white spaces and the unwanted characters from the string or the raw data like CSV file, XML file, or a Text file that can be converted to the string and returns the new string.

How do I change special characters in PowerShell?

Replacing characters or words in a string with PowerShell is easily done using either the replace method or -replace operator. When working with special characters, like [ ], \ or $ symbols, it's often easier to use the replace() method than the operator variant.

How do you use the Replace function in PowerShell?

Using the Replace() MethodThe replace() method has two arguments; the string to find and the string to replace the found text with. As you can see below, PowerShell is finding the string hello and replacing that string with the string hi . The method then returns the final result which is hi, world .

What does $_ in PowerShell mean?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


2 Answers

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

[uri]::EscapeDataString($SitePath) 
like image 60
manojlds Avatar answered Sep 29 '22 21:09

manojlds


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")  
like image 23
Dennis Avatar answered Sep 29 '22 21:09

Dennis