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
} 
4
  • 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 Commented Dec 13, 2018 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). Commented Dec 13, 2018 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? Commented Dec 13, 2018 at 21:24
  • This is a great resource on PSCustomObjects, and the author has an article on hash tables 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! Commented Dec 14, 2018 at 0:57

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.