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

前端 未结 3 1444
既然无缘
既然无缘 2021-02-15 12:13

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:39

    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"
    

提交回复
热议问题