powershellhttpcurl

How to hand headers in curl request in PowerShell windows


curl -X POST <myUrl> -H "authorization: Bearer <valid token>"

But when I send it I get exception - Cannot bind parameter 'Headers'. Cannot convert the "authorization: Bearer " value of type "System.String" to type "System.Collections.IDictionary"


Solution

  • curl is aliased to the Invoke-WebRequest cmdlet in Windows PowerShell.

    As the error message indicates, the -Headers parameter of said cmdlet accepts a dictionary of header key-value pairs.

    Fortunately PowerShell has literal syntax for hash tables:

    @{ key = "value" } 
    

    ... and the [hashtable] type happens to implement the IDictionary interface required by the -Headers parameter.

    So, to pass an Authorization header, you could do:

    Invoke-WebRequest -Uri "<uri goes here>" -Method Post -Headers @{ Authorization = 'Bearer ...' } -UseBasicParsing
    

    (Note that I'm explicitly passing the -UseBasicParsing switch - if not, Windows PowerShell will attempt to parse any HTML response with Internet Explorer's DOM rendering engine, which is probably not what you want in most cases)


    If you need to pass headers with token-terminating characters (like -) in the name, qualify the key(s) with ' quotation marks when constructing the hash table:

    $headers = @{ 
      'Authorization' = 'Bearer ...'
      'Content-Type'  = 'application/json'
    }
    
    Invoke-WebRequest ... -Headers $headers
    

    If header order is important, make sure you declare the hash table/dictionary literal [ordered]:

    $headers = [ordered]@{ 
      'Authorization' = 'Bearer ...'
      'Content-Type'  = 'application/json'
    }
    

    $headers is now guaranteed to enumerate its entries by insertion order (ie. first Authorization, then Content-Type)