I’m making api calls in a for loop and exporting some of the fields from each call to a csv file.
$csvres=foreach ($a in $k)
{
$uri=https://......./$k
$ApiRes= Invoke-RestMethod -uri $uri -Method get -Headers $headers -ContentType 'application/json'
$t=$ApiRes.tags
foreach(($i in $t)
{
if(($i.key -eq "Not enabled") -and (!$ApiRes.state))
{
[PSCustomObject]@{
'Id'=$ApiRes.Id
'State'=$ApiRes.state
'TK'=$ApiRes.key
'TV'=$ApiRes.value
}
}
}
}
$csvres | Export-Csv -path %path -NoTypeInformation
This does work and store all the 4 fields that I want. But the catch the json result from $Apires.tags sometimes has one key and sometimes multiples. So in the csv when it’s single it gets stores properly but when multiple I just get System.Object[].
Consider this as the multiple pair result –
$ApiRes
Id : 510326
type: Type3
state: false
tags: @{active=true;key=Not enabled;value=G78 19/05/2000},@{active=true;key=locked Id}
Position: Not Designated
And this as the single one –
$ApiRes
Id : 998652
type: Type1
state: false
tags: @{active=true;key=Not enabled;value=N52}
Position: Not Designated
The csv with these two looks like –
Id State TK TV
510326 false System.Object[] G78 19/05/2000
998652 false Not enabled N52
This is what I have so far. But even if this system.object gets fixed I am still unable to figure how to export just the key= Not enabled and it’s corresponding value. I do not want the other keys if they are present. Just like it can have multiple keys there can also be values associated with it. I have tried $ApiRes.key[0] $ApiRes.value[0]
but realized that Not enabled wouldn’t always be the first one.
I can filter out only the $k results which has this key using the if condition but am unable to just export this key alone with it’s corresponding value.