0

I am racking my brain over something that is probably simple. I created a custom object. I want to pull each line from the object and use the name and value as variables to put into a function. This will run in a loop until all lines in the object are exhausted. Here is the logic:

# Example: $filename = "rigs" and $url = "https://api.grabme.com/v2/direct-access/rigs?format=xml&page=1&pagesize=1"
$url = @{}
$url.Add("rigs", 'https://api.grabme.com/v2/direct-access/rigs?format=xml&page=1&pagesize=1')
$url.Add("landtrac-units", 'https://api.grabme.com/v2/direct-access/landtrac-units?state_province=Texas&format=xml&page=1&pagesize=1')
$url.Add("trajectories", 'https://api.grabme.com/v2/direct-access/trajectories')

Loop($url) # Loop 3 times
{
    # Call API function
    ApiFunction $filename $url 
    Sleep 5
} 
  • You have created a HashTable, not a custom object. Change `Loop($url)` to `$url.GetEnumerator() | ForEach-Object`, then inside the loop change `$filename` to `$_.Key` and `$url` to `$_.value` – TheMadTechnician Dec 13 '18 at 21:10
  • I agree with @TheMadTechnician but `$URL.GetEnumerator() | ForEach-Object {ApiFunction $_.Name $_.Value;Sleep 5}` (But keep in mind that this will not keep the order of added URLs). –  Dec 13 '18 at 21:14
  • I feel a bit silly assuming this was an object. They seem similar in PowerShell. The order of the URL's isn't a big deal in this case. This runs in a batch and collects the data in CSV files. Would it have been better to create an object with this data? Or is this the right approach? – Paula Erickson Dec 13 '18 at 21:24
  • [This is a great resource on PSCustomObjects](https://kevinmarquette.github.io/2016-10-28-powershell-everything-you-wanted-to-know-about-pscustomobject), and the author has [an article on hash tables](https://kevinmarquette.github.io/2016-11-06-powershell-hashtable-everything-you-wanted-to-know-about) on the same site. In the PSCustomObject article, he also goes into converting hashtables into PSCustomObjects. I personally lean towards using PSCustomObjects where possible, but people with a more traditional programming background seem to like hashtables - horses for courses! – LeeM Dec 14 '18 at 00:57

1 Answers1

3

You CAN do it with a hash table, (also with an ordered one)

$url = [ordered]@{}
$url.Add("rigs", 'https://api.grabme.com/v2/direct-access/rigs?format=xml&page=1&pagesize=1')
$url.Add("landtrac-units", 'https://api.grabme.com/v2/direct-access/landtrac-units?state_province=Texas&format=xml&page=1&pagesize=1')
$url.Add("trajectories", 'https://api.grabme.com/v2/direct-access/trajectories')

$URL.GetEnumerator() | ForEach-Object {
    ApiFunction $_.Name $_.Value
    Sleep 5
}