Search code examples
azurepowershellazure-powershellazure-automation

How to match objects in Powershell Azure VMs


I am currently trying to match an object in powershell but getting blank output and I am not sure why. Any guidance would be greatly appreciated. I am trying to match $resourceIDs with the Get-AzVM command. Sample output of resourceIDs and both "Get-AzVM.ID is as follows

/subscriptions/00/resourcegroups/rg-vm1/providers/microsoft.compute/virtualmachines/az-vm1

And here is the code I am running that is getting blank output. Matching the string above to the Get-AzVM command below works but when I do it with a variable there is blank output.

$resourceIDs =((Get-AzPolicyState -Filter "ComplianceState eq 'NonCompliant'" | Where-Object {$_.PolicyDefinitionReferenceId -eq "azure backup should be enabled for virtual machines_1"} | Where-Object {$_.SubscriptionId -eq ""}).resourceID)
Get-AzVM | Where-Object{$_.Id -match $resourceIDs}

Edit: passing Get-AzVM | Where-Object{$_.Id -eq $resourceIDs[0]} works, now I will have to figure out how to loop through all $resourceIDs

Edit: Get-AzVM | Where-Object{$_.Id -in $resourceIDs}

Thanks a lot everyone!


Solution

  • You can use a Foreach loop,

    $resourceIDs =((Get-AzPolicyState -Filter "ComplianceState eq 'NonCompliant'" | Where-Object {$_.PolicyDefinitionReferenceId -eq "azure backup should be enabled for virtual machines_1"} | Where-Object {$_.SubscriptionId -eq ""}).resourceID)
    
    foreach ( $id in $resourceIDs) 
    
    {
    
    Get-AzVM | Where-Object{$_.Id -in $id}
    
    }