Difficulty to access array values

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 1 year and 11 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
Vinny vinchenzo
Posts: 2
Last visit: Tue Mar 22, 2022 2:32 pm

Difficulty to access array values

Post by Vinny vinchenzo »

Hi,

I am querying an API that returns something like this:
  1. $InvokeResponse =
  2.  
  3. VariableA   : 0
  4. VariableB   : 10
  5. records     : {@{id=1234; name=Vince1; secretTemplateId=1111}, @{id=5678; name=Vince2; secretTemplateId=2222}}
Then

I am trying to loop over the ids but powershell does not like it:
  1. foreach ($record in $InvokeResponse.records){
  2.     Write-host "$record.id"
  3.     }
BUT if I do this, it seems to like it:
  1. foreach ($Record in $InvokeResponse.records.id){
  2.     Write-host "$Record"
  3.     }
Does that make sense? I would like to use the first way. Can you tell what am I doing wrong?
Thanks!
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Difficulty to access array values

Post by jvierra »

Your code is not correct PowerShell syntax. All variables start with a "$".

Start here to find out how to use variables: https://www.sapien.com/books_training/W ... werShell-4
gitpowershelluser
Posts: 24
Last visit: Mon Feb 06, 2023 11:30 am
Has voted: 1 time

Re: Difficulty to access array values

Post by gitpowershelluser »

Vinny vinchenzo wrote: Mon Mar 21, 2022 2:56 pm Hi,

I am querying an API that returns something like this:
  1. $InvokeResponse =
  2.  
  3. VariableA   : 0
  4. VariableB   : 10
  5. records     : {@{id=1234; name=Vince1; secretTemplateId=1111}, @{id=5678; name=Vince2; secretTemplateId=2222}}
Then

I am trying to loop over the ids but powershell does not like it:
  1. foreach ($record in $InvokeResponse.records){
  2.     Write-host "$record.id"
  3.     }
BUT if I do this, it seems to like it:
  1. foreach ($Record in $InvokeResponse.records.id){
  2.     Write-host "$Record"
  3.     }
Does that make sense? I would like to use the first way. Can you tell what am I doing wrong?
Thanks!
Maybe
| Select-Object -ExpandProperty Records


I have an api call that returns it’s objects very similar and that was my solution.
This topic is 1 year and 11 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked