I am currently having issues creating a powershell script that taks to an api with Invoke-RestMethod and a loop, I have spent all day trying to figure out where i am going wrong but i have not managed to come up with something.
Here is the code that i am trying to make
$url = "/api/Rest/v1"
$Body = @{
Username = ""
Password = ""
Privatekey = ""
}
$apikey = Invoke-RestMethod -Method 'Post' -Uri $url/Authenticate -Body $body
$headers = @{
'Authorization' = $apikey
}
$allusers = Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers | ft -HideTableHeaders Id
foreach ($userid in $allusers)
{
echo $userid
Invoke-RestMethod -Uri $url/Users/$userid -Method Get -Headers $headers
echo "test"
}
I am not having issues with the veriables $apikey and $allusers as they seem to output what i need but i think my issue is to do with the outbut being in format table but i have tried other methods for the for each and i have no clue where i am going wrong
So i have tested the Invoke-RestMethod commands on there own and they work as exspected but when i try the script above i get the following.
Invoke-RestMethod : {"Message":"User with specified id was not found."}
the output of $allusers displays something like the following for the user ID
dce502ed-e4b6-4b5e-a047-0bf3b34e98c6
dc1e60c1-99a7-479a-a7d6-0dc618c8dd5e
1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3
AKA the following work with no issues and outputs what i need
Invoke-RestMethod -Uri $url/Users/1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3 -Method Get -Headers $headers
I would really appreciate some kind of guidance on this.
CodePudding user response:
The standard advice applies:
Format-*
cmdlets (such asFormat-Table
, whose built-in alias isft
) emit output objects whose sole purpose is to provide formatting instructions to PowerShell's for-display output-formatting system.
In short: only ever useFormat-*
cmdlets to format data for display, never for subsequent programmatic processing - see this answer for more information.
Therefore, remove the | ft -HideTableHeaders Id
pipeline segment and use member-access enumeration to extract all .Id
property values as data.
$allusers = (Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers).Id