简体   繁体   中英

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
    }

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

The Select * | FL 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

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM