|
# Requires: Az PowerShell Module |
|
# Install with: Install-Module -Name Az -Scope CurrentUser |
|
|
|
# ------------------------ |
|
# VARIABLES - EDIT THESE |
|
# ------------------------ |
|
$ManagementGroupId = "<YourManagementGroupID>" # e.g. "mg-root" |
|
|
|
# ------------------------ |
|
# CONNECT TO AZURE |
|
# ------------------------ |
|
Write-Host "Logging into Azure..." -ForegroundColor Cyan |
|
Connect-AzAccount -UseDeviceAuthentication |
|
|
|
# ------------------------ |
|
# GET SUBSCRIPTIONS UNDER MANAGEMENT GROUP |
|
# ------------------------ |
|
Write-Host "Fetching subscriptions under management group '$ManagementGroupId'..." -ForegroundColor Cyan |
|
$subscriptions = Get-AzManagementGroupSubscription -GroupName $ManagementGroupId |
|
|
|
if (-not $subscriptions) { |
|
Write-Host "No subscriptions found under management group $ManagementGroupId" -ForegroundColor Red |
|
exit |
|
} |
|
|
|
# ------------------------ |
|
# PROCESS EACH SUBSCRIPTION |
|
# ------------------------ |
|
$results = @() |
|
|
|
foreach ($sub in $subscriptions) { |
|
$subId = $sub.SubscriptionId |
|
Write-Host "Switching to subscription: $subId" -ForegroundColor Yellow |
|
Set-AzContext -SubscriptionId $subId | Out-Null |
|
|
|
# Get all Key Vaults in subscription |
|
$vaults = Get-AzKeyVault |
|
|
|
foreach ($vault in $vaults) { |
|
try { |
|
# List all secrets in the vault |
|
$secrets = Get-AzKeyVaultSecret -VaultName $vault.VaultName -ErrorAction Stop |
|
|
|
if ($secrets.Count -gt 0) { |
|
$results += [PSCustomObject]@{ |
|
SubscriptionId = $subId |
|
VaultName = $vault.VaultName |
|
ResourceGroup = $vault.ResourceGroupName |
|
Location = $vault.Location |
|
SecretCount = $secrets.Count |
|
} |
|
} |
|
} |
|
catch { |
|
# Skip vaults where we can't list secrets (lack of permissions) |
|
Write-Host "Skipping vault '$($vault.VaultName)' due to permissions or other errors." -ForegroundColor DarkGray |
|
} |
|
} |
|
} |
|
|
|
# ------------------------ |
|
# OUTPUT RESULTS |
|
# ------------------------ |
|
if ($results.Count -gt 0) { |
|
Write-Host "Vaults with secrets found:" -ForegroundColor Green |
|
$results | Format-Table -AutoSize |
|
|
|
# Optional: Export to CSV |
|
$csvPath = ".\AzureKeyVaultsWithSecrets.csv" |
|
$results | Export-Csv -Path $csvPath -NoTypeInformation |
|
Write-Host "Results exported to $csvPath" -ForegroundColor Cyan |
|
} |
|
else { |
|
Write-Host "No vaults with secrets found under management group '$ManagementGroupId'." -ForegroundColor Red |
|
} |