1
votes

I am currently trying to pull data from an Azure policy for some automation with:

(Get-AzPolicyState -Filter "ComplianceState eq 'NonCompliant'" | Where-Object {$.PolicyDefinitionReferenceId -eq "azure backup should be enabled for virtual machines_1"} | Where-Object {$.SubscriptionId -eq "0000"}).ResourceId

Type Name: System.String

Example output

/subscriptions/00/resourcegroups/rg-test/providers/microsoft.compute/virtualmachines/vm-test

/subscriptions/00/resourcegroups/rg-test2/providers/microsoft.compute/virtualmachines/vm-test2

I am confused on how I can just pull the resource group name and virtual machine name only into a variable array. The resource group name is always preceded by /resourcegroups/ and VM name is always preceded by /virtualmachines/.

Any guidance would be greatly appreciated. Thank you!

1
$rg,$vm= '/subscriptions/00/resourcegroups/rg-test/providers/microsoft.compute/virtualmachines/vm-test' -replace '^.*/resourcegroups/([^/]+)/.*virtualmachines/([^/]+)','$1/$2' -split '/'AdminOfThings
How's going? Has your issue got solved?Stanley Gong

1 Answers

1
votes

If you just want to extract your VM name and groupName from resourceID, just try the code below:

function parseGroupAndName{
     param (
        [string]$resourceID
    )
    $array = $resourceID.Split('/') 
    $indexG = 0..($array.Length -1) | where {$array[$_] -eq 'resourcegroups'}
    $indexV = 0..($array.Length -1) | where {$array[$_] -eq 'virtualmachines'}
    $result = $array.get($indexG+1),$array.get($indexV+1)
    return $result
}

$resourceID = '/subscriptions/00/resourcegroups/rg-test/providers/microsoft.compute/virtualmachines/vm-test'

parseGroupAndName -resourceID $resourceID

Result: enter image description here