Scripts/Get-AzKeyVaultAccessPolicies.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
param(
   [string][parameter(Mandatory = $true)] $keyVaultName,
   [string][parameter(Mandatory = $false)] $resourceGroupName = ""
)

$keyVault = $null
if($resourceGroupName -eq '')
{
    Write-Host "Looking for the Key Vault with name '$keyVaultName'."
    $keyVault = Get-AzKeyVault -VaultName $keyVaultName
}
else
{
    Write-Host "Looking for the Key Vault with name '$keyVaultName' in resourcegroup '$resourceGroupName'"
    $keyVault = Get-AzKeyVault -VaultName $keyVaultName -ResourceGroupName $resourceGroupName
}

if($keyVault)
{
    $armAccessPolicies = @()
    $keyVaultAccessPolicies = $keyVault.accessPolicies

    if($keyVaultAccessPolicies)
    {
       Write-Host "Key Vault '$keyVaultName' is found."

       foreach($keyVaultAccessPolicy in $keyVaultAccessPolicies)
       {
          $armAccessPolicy = [pscustomobject]@{
             tenantId = $keyVaultAccessPolicy.TenantId
             objectId = $keyVaultAccessPolicy.ObjectId
          }

          $armAccessPolicyPermissions = [pscustomobject]@{
             keys =  $keyVaultAccessPolicy.PermissionsToKeys
             secrets = $keyVaultAccessPolicy.PermissionsToSecrets
             certificates = $keyVaultAccessPolicy.PermissionsToCertificates
             storage = $keyVaultAccessPolicy.PermissionsToStorage
          }

          $armAccessPolicy | Add-Member -MemberType NoteProperty -Name permissions -Value $armAccessPolicyPermissions

          $armAccessPolicies += $armAccessPolicy
       }   
    }

    $armAccessPoliciesParameter = [pscustomobject]@{
        list = $armAccessPolicies
    }

    Write-Host "Current access policies: $armAccessPoliciesParameter"
    return $armAccessPoliciesParameter
}
else
{
    Write-Warning "KeyVault '$keyVaultName' could not be found."
}