Milister
Milister

Reputation: 658

Powershell - Invoke-RestMethod get VM name

trying to list all Azure VM's using https://b-blog.info/en/monitoring-azure-resources-with-zabbix.html

$uri = "https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines?api-version=2017-12-01" -f `
    $subscription_id, `
    $resource_group;
write-host $uri
https://management.azure.com/subscriptions/111111-1111-111-11111-111/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines?api-version=2017-12-01

this code gives output (currently have only one VM)

Invoke-RestMethod -Uri $uri -Headers $azure_header -Method Get -ErrorAction Stop | select * | fl

value : {@{properties=; type=Microsoft.Compute/virtualMachines; location=westeurope; id=/subscriptions/111111-222-1111-1111-111111/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/test; name=test}}

this line (as per link above) gives nothing:

$a=(Invoke-RestMethod -Uri $uri -Headers $azure_header -Method Get -ErrorAction Stop | select * | fl ).content.properties;

write-host $a gives nothing and next line is also empty (get VM name)

foreach ($machine in $machines) {
$uri = https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}?api-version=2017-12-01" -f `
        $subscription_id, `
        $resource_group, `
        $machine.name;
    write-host $machine.name
    }

Upvotes: 0

Views: 344

Answers (2)

Jacob Colvin
Jacob Colvin

Reputation: 2835

FL formats the object as a string, thus you cannot expand any properties from it.

The Select * | FL in your case is unnecessary and only impedes you. Removing it should get data to start returning.

EDIT: I got the correct property name just from looking through your JSON.

(Invoke-RestMethod -Uri $uri -Headers $azure_header -Method Get -ErrorAction Stop).value.properties.osProfile.computerName

Upvotes: 1

Milister
Milister

Reputation: 658

@Avshalom I found solution thanks to you (leave only Value property):

$a=(Invoke-RestMethod -Uri $uri -Headers $azure_header -Method Get -ErrorAction Stop).Value
Write-Host $a.name

output:test

Upvotes: 0

Related Questions