Powershell - Invoke-WebRequest to a URL with literal '/' (/) in it

前端 未结 3 1392
半阙折子戏
半阙折子戏 2021-02-15 11:53

I have been trying to access a URL with a / character in it from powershell, using the following command (it\'s a query to a gitlab server to retrieve a project ca

3条回答
  •  孤城傲影
    2021-02-15 12:47

    Here is an alternate port of https://stackoverflow.com/a/784937/2864740 - it accepts a string and returns a new URI.

    function CreateUriWithoutIncorrectSlashEncoding {
        param(
            [Parameter(Mandatory)][string]$uri
        )
    
        $newUri = New-Object System.Uri $uri
    
        [void]$newUri.PathAndQuery # need to access PathAndQuery (presumably modifies internal state)
        $flagsFieldInfo = $newUri.GetType().GetField("m_Flags", [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic)
        $flags = $flagsFieldInfo.GetValue($newUri)
        $flags = $flags -band (-bnot 0x30) # remove Flags.PathNotCanonical|Flags.QueryNotCanonical (private enum)
        $flagsFieldInfo.SetValue($newUri, $flags)
    
        $newUri
    }
    

    Usage:

    $uri = CreateUriWithoutIncorrectSlashEncoding "https://server.com/api/v3/projects/foo%2Fbar"
    

提交回复
热议问题