Powershell create array of arrays

前端 未结 3 1775
失恋的感觉
失恋的感觉 2021-01-16 07:09

I\'m trying to push data to a REST api using powershell.

http://influxdb.com/docs/v0.8/api/reading_and_writing_data.html

The server expects data like so:

3条回答
  •  耶瑟儿~
    2021-01-16 07:29

    Just to add my two pence worth. Its is worth noting that everytime you touch an array and you know is a single item array, you must use the appropriate comma syntax. This is not well highlighted in articles I found on the subject.

    Take this example case I wrote for a Pester test case:

    A lesson about single item arrays, every time you touch a single item array, you must use the comma op. It is not a case of set it and forget it:

            Mock get-AnswerAdvancedFn -ModuleName Elizium.Loopz {
              $pairs = @(, @('Author', 'Douglas Madcap Adams'));
              $first = $pairs[0];
              Write-Host "=== SINGLE-ITEM: pairs.count: $($pairs.Count), first.count: $($first.Count)"
              ([PSCustomObject]@{ Pairs = $pairs })
            }
    

    The above won't work, because of the fault assigning $pairs to Pairs even though we've used the correct syntax setting $pairs to @(, @('Author', 'Douglas Madcap Adams'))

    The following fixes this issue; everytime you touch the single item array, you must use the comma syntax, otherwise you give PowerShell another chance to flatten your array:

            Mock get-AnswerAdvancedFn -ModuleName Elizium.Loopz {
              $pairs = @(, @('Author', 'Douglas Madcap Adams'));
              $first = $pairs[0];
              Write-Host "=== SINGLE-ITEM: pairs.count: $($pairs.Count), first.count: $($first.Count)"
              ([PSCustomObject]@{ Pairs = , $pairs })
            }
    

    My test code ended up being this:

            Mock get-AnswerAdvancedFn -ModuleName Elizium.Loopz {
              ([PSCustomObject]@{ Pairs = , @(, @('Author', 'Douglas Madcap Adams')) })
            }
    

    Note, we had to use the comma op twice and both of those are necessary

提交回复
热议问题