Powershell:Cannotconvertthe"System.Collections.Hashtable"valueoftype"System.Collections.Hashtable"totype"System.Uri"

Goal: I want to send a POST API request to JIRA with irm (Invoke-RestMethod).

Environment:

  • OS: Windows 10 64 bit
  • Powershell 5 (I think it's 5, it's the default that comes with Windows)

Script:

$Body = @{
    'fields' = @{
       'project' = @{'key' = 'ABC'}
       'summary' = "summary"
       'description' =  "desc"
       'issuetype' = @{'name' = 'Test'}
       'assignee' = 'user'
   }
}

$JsonBody = ($Body | ConvertTo-Json)

$params = @{
    Uri         = "https://jira.myjira.co.uk/rest/api/latest/issue"
    Headers     = @{ "Authorization" = "Basic myToken" }
    Method      = "POST"
    Body        = $JsonBody
    ContentType = "application/json"
}

$response = irm $params
$response | Out-File test.txt

When I execute it, I get the message below. Powershell is complaining but I don't know what is wrong with my parameters.

Invoke-RestMethod : Cannot bind parameter 'Uri'. Cannot convert the "System.Collections.Hashtable" value of type
"System.Collections.Hashtable" to type "System.Uri".
At C:UsersUserDownloadsMyScript.ps1:64 char:17
+ $response = irm $params
+                 ~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-RestMethod], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

What I've tried:

  • Executed it in ISE and it does the same thing
  • I used the @params format for another script and it was fine. I wonder if the issue is with the Uri part...
  • Googling and looking at stackoverflow, there was similar matches but doesn't fit my scenario

Any help is appreciated, I've been banging my head against a wall for an hour.

回答

Simply change the $params to @params, this is called splatting.

"Splatting is a method of passing a collection of parameter values to a command as a unit."

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.1

$response = irm @params


以上是Powershell:Cannotconvertthe"System.Collections.Hashtable"valueoftype"System.Collections.Hashtable"totype"System.Uri"的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>