How do I replace spaces with in PowerShell?

前端 未结 4 1526
终归单人心
终归单人心 2020-12-29 18:47

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, \"%2

相关标签:
4条回答
  • 2020-12-29 19:14

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

    [uri]::EscapeDataString($SitePath)
    
    0 讨论(0)
  • 2020-12-29 19:24

    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.

    0 讨论(0)
  • 2020-12-29 19:26

    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

    0 讨论(0)
  • 2020-12-29 19:27

    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") 
    
    0 讨论(0)
提交回复
热议问题