0
votes

I am looking writing a PowerShell script that calls an API using the Invoke-RestMethod. Below is the output from the command. I am looking to only return a line that matches the current hostname of the server running the PowerShell script, then take the number from the id= field and put that into a variable.

Any help would be greatly appreciated.

Command:

Invoke-RestMethod -Uri http://xxx.xxx.xxx.xxx/api/hosts -Headers @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password ))} -Method GET

Output:

host

@{name=dns01.aws.local; id=4; hostgroup_id=3; operatingsystem_id=3}
@{name=win-9d3nna26g9c.aws.local; id=56; hostgroup_id=5; operatingsystem_id=2}

UPDATE:

I am getting closer the below command will just return the line with the computer name, and filter only the name and id. Now I just need to get that id value into a variable, which I am having trouble figuring out, any help would be appreciated.

(Invoke-RestMethod -Uri http://xxx.xxx.xxx.xxx/api/hosts -Headers @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password ))}).host | Select-Object name,id | Where-Object name -Like "$env:COMPUTERNAME"

Output:

name id
---- --
win-9d3nna26g9c.aws.ths 56

2

2 Answers

0
votes

I don't have your input, so I can't be 100% sure this will work perfectly, but I believe you're after:

Invoke-RestMethod ... |
    ConvertFrom-Json | 
    Where-Object { $_.Name -eq $env:ComputerName } |
    Select-Object -ExpandProperty ID
0
votes

Here is the final code I was able to get working for what I needed done.

$foremanhost = (Invoke-RestMethod -Uri http://xxx.xxx.xxx.xxx/api/hosts -Headers @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password ))}).host | Select-Object name,id | Where-Object name -Like "$env:COMPUTERNAME" $foreman = ($foremanhost | Select-Object -Expand id) Invoke-WebRequest -Uri http://xxx.xxx.xxx.xxx/api/hosts/$foreman -Headers @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password ))} -Body $json -ContentType application/json -Method PUT