Powershell script Missingtypename

Viewed 150

I am trying to make some API calls through powershell using this documentation https://octopus.com/blog/manually-push-build-information-to-octopus

        $Headers = @{"X-Octopus-ApiKey"=$MYKEY"}
        $jsonBody = @{
            PackageId = "Test"
            Version = "1.1.1"
            OctopusBuildInformation =
                @{
                    BuildEnvironment = "Jenkins"
                    BuildNumber = "1"
                    BuildURL = "myURL"
                    VcsCommitNumber = "250"
                    VcsType = "Git"

                    Commits = [{Id = "250" LinkUrl = "gitUrl" Comment = "someComment"}]
                    VcsRoot = "gitUrl"
                }
         } | ConvertTo-Json -Depth 5

        Invoke-RestMethod -Method Post -Uri "http://alfadeployment/api/build-information" -Headers $Headers -Body $jsonBody

However, since I added the commits array, I am getting the following error:

  Missing type name after '['.
      + CategoryInfo          : ParserError: (:) [], ParseException
      + FullyQualifiedErrorId : MissingTypename
1 Answers

PowerShell arrays aren't enclosed in [...] - the latter is used for type literals, i.e. to refer to .NET types - hence the error message.

You may - but don't have to - enclose PowerShell arrays in @(...), the array-subexpression operator; using ,, the array constructor operator is enough, though @(...) can be helpful for visual clarity, and to create an empty (@()) or single-element arrays (@('foo')), which is perhaps clearer than the unary use of , (, 'foo')).

Additionally, the array element in your case must be a hashtable too (@{ ... }, not { ... }, the latter is a script block), and, given that the property definitions are on the same line, they must be ;-separated.

To put it all together:

Commits = @(
  @{ Id = "250"; LinkUrl = "gitUrl"; Comment = "someComment" }
)
Related