0

I am currently trying to create a foreach loop to take each value from a list and search for it in return data from an API. For some reason I am getting NULL data when I try to loop it.

$agentList = (Import-CSV -Path 'O:\Test\AgentList.txt')

$Params = @{
    "Uri"     = "https://10.245.55.88:8834/agents"
    "Method"  = "GET"
    "Headers" = @{
        "X-ApiKeys" = "accessKey=$($AccessKey); secretKey=$($SecretKey)"
    }
}

$agentsNotInSC = Invoke-Restmethod @Params

$agentID = foreach ($agent in $agentList) {
    $agentID = $agentsNotInSC.agents | Where-Object { $_.name -eq $agent }
    $agentID.id
}

$agentID | Export-Csv -Path "O:\Test\IDAgent.CSV" -NoTypeInformation

trying to get all the return data and export it to a CSV

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Derek
  • 1
  • Can you show us what the resulting CSV looks like? – Mathias R. Jessen Feb 07 '23 at 15:58
  • You are using `Import-Csv` to read a .txt file, which doesn't look right. If this file is just a list of names, use `$agentList = Get-Content 'O:\Test\AgentList.txt'` instead. – zett42 Feb 07 '23 at 16:08
  • Not sure if this is the fix but try adding $agentID = @() before you go to the foreach. – Bee_Riii Feb 07 '23 at 16:08
  • You don't need to define `$agentID =` twice; you've got it at the start of your foreach, and again within the foreach. That'll keep getting changed. You need to make $agentID outside of the foreach an array, and add objects to that array - otherwise it's just a string, and you're changing what it equals each time. Finally, you should check that the names in $agentList and $agentsNotInSC.agents match manually - they might be formatted differently, hence the -eq not working – Anthony Norwood Feb 07 '23 at 16:19
  • As an aside, I think you can simplify your code a bit to something like this: ```$agentID = @($agentsNotInSC.agents | where-object { $_.name -in $agentList }).id```, assuming ```$agentList``` is an array of strings per @zet42's comment... – mclayton Feb 07 '23 at 16:39

0 Answers0