-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParse-ResourceId.ps1
65 lines (55 loc) · 2.68 KB
/
Parse-ResourceId.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function Parse-ResourceId
{
[CmdletBinding()]
param
(
[Parameter(valueFromPipeline = $true, mandatory = $true)]
[ValidatePattern("(/\w+/)([a-fA-F\d]{8}-([a-fA-F\d]{4}-){3}[a-fA-F\d]{12})(/\w+/)([\d\w-_]+)(/\w+/)([\w+.]+)([/\w+/)([\d\w-_]+)")]
[string]$resourceId
)
try
{
$resourceId = $resourceId.ToLower();
$resourceHash = @{};
# subscriptionId
$subscriptionId = [regex]::Match($resourceId, "[a-fA-F\d]{8}-([a-fA-F\d]{4}-){3}[a-fA-F\d]{12}").value;
$resourceHash.Add("subscriptionId", $subscriptionId);
# resource group
$resourceGroup = [regex]::Match($resourceId, "resourcegroups/([\d\w-_]+)").value.replace("resourcegroups/", "");
$resourceHash.Add("resourceGroup", $resourceGroup);
# parent resource
$resourceValue = [regex]::Match($resourceid, "providers/([\w+.]+)(/\w+/)([\w-_]+)").value;
$resourceValue = [regex]::Replace($resourceValue, "providers/([\w+.]+)(/\w+/)", "");
$resourceProvider = [regex]::Match($resourceid, "providers/([\w+.]+)(/\w+/)([\w-_]+)").value;
$resourceProvider = [regex]::Replace($resourceProvider, "providers/([\w+.]+)/", "");
$resourceProvider = $resourceProvider.Substring(0, $resourceProvider.IndexOf("/"));
$resourceHash.Add($resourceProvider, $resourceValue);
# recurse child resources
$childResources = $resourceid.Substring($resourceid.IndexOf($resourceValue)).Replace("$resourceValue/", "");
if ([regex]::Match($childResources, "/").success -eq $true)
{
do
{
$match = [regex]::Match($childResources, "/");
$childResourceProvider = [regex]::Match($childResources, "([\w+-]+)/").value;
$childResourceProviderValue = $childResources.Replace($childResourceProvider, "");
$childresources = $childResourceProviderValue.Substring($childResourceProviderValue.IndexOf("/") + 1);
if ([regex]::Match($childResourceProviderValue, "/").success -eq $true)
{
$childResourceProviderValue = $childResourceProviderValue.Substring(0, $childResourceProviderValue.IndexOf("/"));
}
$resourceHash.Add($childResourceProvider.replace("/", ""), $childResourceProviderValue);
if ([regex]::Match($childResources, "/").success -eq $false)
{
break;
}
}
while ($match.success -eq $true)
}
}
catch [exception]
{
Write-Error -Message "Error parsing the resourceId! $($_.exception)";
}
return $resourceHash;
}