Reputation: 85
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!
Upvotes: 3
Views: 3288
Reputation: 4544
In most cases, all I need is the resource name. For that, the following code solves the trick:
$vmId.Split('/') | Select-Object -Last 1
Upvotes: 0
Reputation: 131
more simple :
$resourceID = '/subscriptions/xxxx/resourceGroups/rrrrrrr/providers/aaaa/bbbb/nnnnn'
$cc=Get-AzResource -ResourceId
$cc.ResourceType
aaaaa/bbbb
$cc.ResourceGroupName
rrrrrr
$cc.Name
nnnnnnn
Upvotes: 1
Reputation: 12153
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
Upvotes: 2