Az.Plus.psm1
# Az.Accounts $authModuleName = 'Az.Accounts' $authModuleVersion = '2.7.5' $authModule = Get-Module -Name $authModuleName if(-not $authModule) { if(-not $authModule) { $hasAdequateVersion = (Get-Module -Name $authModuleName -ListAvailable | Where-Object { $_.Version -ge [System.Version]$authModuleVersion } | Measure-Object).Count -gt 0 if($hasAdequateVersion) {$authModule = Import-Module -Name $authModuleName -MinimumVersion $authModuleVersion -Scope Global -PassThru} } } if(-not $authModule) { Write-Error "`nThis module requires $authModuleName version $authModuleVersion or greater. For installation instructions, please see: https://docs.microsoft.com/powershell/azure/install-az-ps" -ErrorAction Stop } elseif ($authModule.Version -lt [System.Version]$authModuleVersion) { Write-Error "`nThis module requires $authModuleName version $authModuleVersion or greater. An earlier version of Az.Accounts is imported in the current PowerShell session.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop } <# .SYNOPSIS Get-AzAppServiceRuntimeVersion .DESCRIPTION Get Azure App Service runtime version (webapp + function) .NOTES (c) 2023 JDMSFT. All rights reserved. Function developed using following modules: 2.10.4 Az.Accounts 4.0.6 Az.Functions 0.13.0 Az.ResourceGraph .EXAMPLE Get-AzAppServiceRuntimeVersion #> Function Get-AzAppServiceRuntimeVersion { # Function App $resources = Search-AzGraph 'resources | where type == "microsoft.web/sites" and kind == "functionapp" | project id, kind, state = properties.state' -UseTenantScope $resources | % { $functionApp = $null $appSettings = $null $functionApp = Get-AzFunctionApp -SubscriptionId $_.ResourceId.Split('/')[2] -ResourceGroupName $_.ResourceId.Split('/')[4] -Name $_.ResourceId.Split('/')[8] $appSettings = $functionApp.ApplicationSettings [array]$pso += [PSCustomObject]@{resourceId = $_.ResourceId; kind = $_.Kind; state = $_.state ; system = $functionApp.OSType ; runtimeWorker = $appSettings.FUNCTIONS_WORKER_RUNTIME; runtimeVersion = $appSettings.FUNCTIONS_EXTENSION_VERSION } } # WebApp $resources = Search-AzGraph 'resources | where type == "microsoft.web/sites" and kind != "functionapp" | mv-expand FxVersion = properties.siteProperties.properties | where isnotempty(FxVersion.value) | extend system = iff(FxVersion.name == "LinuxFxVersion", "Linux", "Windows") | extend runtimeWorker = split(FxVersion.value,"|")[0] | extend runtimeVersion = split(FxVersion.value,"|")[1] | project id, kind, state=properties.state, system, runtimeWorker, runtimeVersion' -UseTenantScope $resources | % {[array]$pso += [PSCustomObject]@{resourceId = $_.ResourceId; kind = 'webapp'; state = $_.state ; system = $_.system ; runtimeWorker = $_.runtimeWorker; runtimeVersion = $_.runtimeVersion }} $pso } <# .SYNOPSIS Get-AzSqlDatabaseBackupPolicy .DESCRIPTION Get Azure Database for SQL Backup Policy .NOTES (c) 2023 JDMSFT. All rights reserved. Function developed using following modules: 2.10.4 Az.Accounts 4.1.0 Az.Sql .EXAMPLE Get-AzSqlDatabaseBackupPolicy #> Function Get-AzSqlDatabaseBackupPolicy { Get-AzSqlServer | % { Get-AzSqlDatabase -ResourceGroupName $_.ResourceGroupName -ServerName $_.ServerName -wa SilentlyContinue | % { If (($_.DatabaseName -ne 'master') -and ($_.SkuName -ne 'DataWarehouse')) { $str = $_ | Get-AzSqlDatabaseBackupShortTermRetentionPolicy $ltr = $_ | Get-AzSqlDatabaseBackupLongTermRetentionPolicy [array]$sqlBackupPolicies += [PSCustomObject]@{ SubscriptionId = $_.ResourceId.Split('/')[2] ResourceGroupName = $_.ResourceGroupName ServerName = $_.ServerName DatabaseName = $_.DatabaseName DatabaseSku = $_.SkuName StrInDays = $str.RetentionDays StrDiffBackupInHours = $str.DiffBackupIntervalInHours StrRedundancyCurrent = $_.CurrentBackupStorageRedundancy StrRedundancyRequested = $_.RequestedBackupStorageRedundancy LtrEnabled = if ($ltr.location -eq $null) { $false } Else { $true } LtrStorageLocation = $ltr.location LtrWeeklyRetention = $ltr.WeeklyRetention LtrMonthlyRetention = $ltr.MonthlyRetention LtrYearlyRetention = $ltr.YearlyRetention LtrWeekOfYear = $ltr.WeekOfYear } } } } If ($sqlBackupPolicies) { $sqlBackupPolicies } Else { Write-Warning "No user database in current context ($((Get-AzContext).Subscription.Name))." } } <# .SYNOPSIS Get-AzStorageBlobBackupSettings .DESCRIPTION Get Azure Blob Backup Policy .NOTES (c) 2023 JDMSFT. All rights reserved. Function developed using following modules: 2.10.4 Az.Accounts 5.2.0 Az.Storage .EXAMPLE Get-AzStorageBlobBackupSettings #> Function Get-AzStorageBlobBackupSettings { Get-AzStorageAccount | % { $saType = $_.Kind $saTier = $($_.Sku).Name $SaBlobSettings = Get-AzStorageBlobServiceProperty -ResourceGroupName $_.ResourceGroupName -StorageAccountName $_.StorageAccountName If (($SaBlobSettings.RestorePolicy.Enabled -eq $true) -and ($SaBlobSettings.DeleteRetentionPolicy.Enabled -eq $true) -and ($SaBlobSettings.ChangeFeed.Enabled -eq $true) -and ($SaBlobSettings.IsVersioningEnabled -eq $true)) { $BackupEnabled = $true } Else { $BackupEnabled = $false } If (($saType -eq 'StorageV2') -and ($saTier -match 'Standard')) { $BackupSupported = $true } Else { $BackupSupported = $false } [array]$pso += [PSCustomObject]@{name = $SaBlobSettings.StorageAccountName; Type = $saType ; Tier = $saTier ; BackupSupported = $BackupSupported ; BackupEnabled = $BackupEnabled ; RestorePolicyEnabled = $SaBlobSettings.RestorePolicy.Enabled ; DeleteRetentionPolicyEnabled = $SaBlobSettings.DeleteRetentionPolicy.Enabled ; ChangeFeedEnabled = $SaBlobSettings.ChangeFeed.Enabled ; VersioningEnabled = $SaBlobSettings.IsVersioningEnabled } } If ($pso) {$pso} Else { Write-Warning "No blob storage account in current context ($((Get-AzContext).Subscription.Name))." } } <# .SYNOPSIS Get-AzStorageAccountUsageDetails .DESCRIPTION Get Azure Storage Account usage details .NOTES (c) 2023 JDMSFT. All rights reserved. Function developed using following modules: 2.10.4 Az.Accounts 5.2.0 Az.Storage .EXAMPLE Get-AzStorageAccountUsageDetails #> Function Get-AzStorageAccountUsageDetails { param([switch]$TenantScope) Write-Warning 'Non-user blob containers like $logs are skipped from NumberOfContainers count property' If ($TenantScope) { Write-Warning 'Azure Active Directory subscriptions excluded from scope.' ; Get-AzSubscription | % { If ($_.Name -notmatch "Azure Active Directory") { Select-AzSubscription $_ | Out-Null ; [array]$output += Get-AzStorageAccountUsageDetails_INTERNAL -wa SilentlyContinue } } ; $output } Else { Get-AzStorageAccountUsageDetails_INTERNAL -wa SilentlyContinue } } Function Get-AzStorageAccountUsageDetails_INTERNAL { [CmdletBinding()] param() Write-Warning 'Non-user blob containers like $logs are skipped from NumberOfContainers count property' Get-AzStorageAccount | % { $shares = $null $queues = $null $tables = $null $containers = (Get-AzStorageContainer -Context $_.Context).Count if ($_.PrimaryEndpoints.File) { $shares = (Get-AzStorageShare -Context $_.Context).Count } if ($_.PrimaryEndpoints.Queue) { $queues = (Get-AzStorageQueue -Context $_.Context).Count } if ($_.PrimaryEndpoints.Table) { $tables = (Get-AzStorageTable -Context $_.Context).Count } [array]$pso += [PSCustomObject]@{StorageAccountName = $_.StorageAccountName; Kind = $_.Kind ; Sku = $_.Sku.Name ; NumberOfContainers = $containers; NumberOfShares = $shares ; NumberOfQueues = $queues ; NumberOfTables = $tables } } If ($pso) { $pso } Else { Write-Warning "No storage account in current context ($((Get-AzContext).Subscription.Name))." } } <# .NOTES ============================================================================================== DISCLAIMER ============================================================================================== This script is not supported under any Microsoft standard support program or service. This script is provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the script and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the script be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages. ============================================================================================== PREREQUISITES ============================================================================================== Az.Accounts (2.9.0) Az.Resources (6.0.1) .SYNOPSIS Get all role assignments for a specific user account .DESCRIPTION Get all role assignments at all scope for a specific Azure Active Directory user account .PARAMETER UserAccount Specify the sign in name of the user account (ex: account@domain.tld). .EXAMPLE C:\PS> .\Get-AzUserRoleAssignment.ps1 -UserAccount account@domain.tld #> Function Get-AzUserRoleAssignment { Param ([Parameter(Mandatory = $true)][string]$UserAccount) Try { $WarningPreference = 'SilentlyContinue'; $assignments = @(); Get-AzManagementGroup | % { $assignments += Get-AzRoleAssignment -Scope $_.Id -SignInName $UserAccount -ea SilentlyContinue | select Scope, RoleDefinitionName } Get-AzSubscription | % { Select-AzSubscription $_ | Out-Null ; $assignments += Get-AzRoleAssignment -SignInName $UserAccount -ea SilentlyContinue | select Scope, RoleDefinitionName }; $assignments } Catch { Write-Error -Message $_.Exception; throw $_.Exception } } <# .SYNOPSIS Get-AzTenantAvailabilityZones .DESCRIPTION Get Azure tenant avaiability zones map (subscription availability zones) .NOTES (c) 2023 JDMSFT. All rights reserved. Function developed using following modules: 2.10.4 Az.Accounts .EXAMPLE Get-AzTenantAvailabilityZones #> Function Get-AzTenantAvailabilityZones { Param ([Parameter(Mandatory = $true)][string]$Location = 'francecentral') $zonesLocation = $Location $token = Get-AzAccessToken $headers = @{ Authorization = "$($token.Type) $($token.Token)" ContentType = 'application/json' } $req = ((iwr -Method POST -Uri "https://management.azure.com/subscriptions/$((Get-AzContext).Subscription.Id)/providers/Microsoft.Resources/checkZonePeers/?api-version=2020-01-01" -Headers $headers -Body (@{location = $zonesLocation; subscriptionIds = Get-AzSubscription | % { 'subscriptions/' + $_.Id } } | ConvertTo-Json) -ContentType $headers.ContentType).Content | ConvertFrom-Json).availabilityZonePeers $req | % { $zone = $_.availabilityZone $_.peers | % { [array]$pso += [PSCustomObject]@{SubscriptionId = $_.subscriptionId ; SubscriptionZone = $_.availabilityZone ; AvailabilityZone = $zone } } } If ($pso) { $pso } Else { Write-Warning "Please verify context, location and if the right provider is registered on current subscription(Register-AzProviderFeature -FeatureName AvailabilityZonePeering -ProviderNamespace Microsoft.Resources) ($((Get-AzContext).Subscription.Name))." } } <# .SYNOPSIS Export-AzTenantResourceGroupWithTags .DESCRIPTION Export all resource groups with tags from all subscription or a set of subscriptions .PARAMETER Path Path Set path destination to export csv file .EXAMPLE C:\PS> .\Export-AzTenantResourceGroupWithTags.ps1 -Path D:\allRgsWithTags.csv #> Function Export-AzTenantResourceGroupWithTags { [CmdletBinding()] param ([string]$Path = "./export_2022.csv", [array]$SubscriptionNames = $null) $TenantId = (Get-AzContext).Tenant.Id If ($SubscriptionNames) { $Subscriptions = @() ; $SubscriptionNames | % { $Subscriptions += Get-AzSubscription -SubscriptionName $_ -TenantId $TenantId } } Else { $Subscriptions = Get-AzSubscription -TenantId $TenantId } #Schema $Schema = @() $Subscriptions | % { Select-AzSubscription $_ -TenantId $TenantId | Out-Null $ResourceGroups = Get-AzResourceGroup If ($ResourceGroups) { $ResourceGroupTags = $ResourceGroups.Tags If ($ResourceGroupTags) { $Tags = $ResourceGroupTags.Keys | Select-Object -Unique $Schema += $Tags } } } $schema = $schema | Sort-Object -Unique #Output $Output = @() $Subscriptions | % { Select-AzSubscription $_ -TenantId $TenantId | Out-Null $SubId = $_.Id $SubName = $_.Name $ResourceGroups = Get-AzResourceGroup If ($ResourceGroups) { $Tags = $ResourceGroupTags.Keys | Select-Object -Unique foreach ($ResourceGroup in $ResourceGroups) { $RGHashtable = [ordered] @{} $RGHashtable.Add("SubscriptionId", $SubId) $RGHashtable.Add("SubscriptionName", $SubName) $RGHashtable.Add("ResourceGroupName", $ResourceGroup.ResourceGroupName) $RGHashtable.Add("Location", $ResourceGroup.Location) $RGHashtable.Add("ResourceId", $ResourceGroup.ResourceId) $RGHashtable.Add("ProvisioningState", $ResourceGroup.ProvisioningState) if ($ResourceGroup.Tags.Count -ne 0) { $Schema | Foreach-Object { if ($ResourceGroup.Tags[$_]) { $RGHashtable.Add("$_ (Tag)", $ResourceGroup.Tags[$_]) } else { $RGHashtable.Add("$_ (Tag)", $null) } } } else { $Schema | Foreach-Object { $RGHashtable.Add("$_ (Tag)", $null) } } $Output += New-Object psobject -Property $RGHashtable } } } #$Schema #$Output $Output | Export-Csv -Path $Path -Delimiter ';' -NoTypeInformation -Encoding UTF8 -Force } <# .SYNOPSIS Connect-AzAdReaderAccount .DESCRIPTION Connect to Azure Active Directory as reader (read only mode) .NOTES (c) 2023 JDMSFT. All rights reserved. Function developed using following modules: 1.27.0 Microsoft.Graph.Authentication 1.27.0 Microsoft.Graph.DeviceManagement.Enrolment .EXAMPLE Connect-AzAdReaderAccount #> Function Connect-AzAdReaderAccount { Param ([Parameter(Mandatory = $false)][string]$TenantId) If ($TenantId) {Connect-MgGraph -Scopes "RoleManagement.Read.Directory, Directory.Read.All" -TenantId $TenantId} Else {Connect-MgGraph -Scopes "RoleManagement.Read.Directory, Directory.Read.All"} } <# .SYNOPSIS Get-AzServicePrincipalAadRoleAssignments .DESCRIPTION Get all Azure AD role assignments for a specific service principal / managed identity by specifying object/principal id .NOTES (c) 2023 JDMSFT. All rights reserved. Function developed using following modules: 1.27.0 Microsoft.Graph.Authentication 1.27.0 Microsoft.Graph.DeviceManagement.Enrolment .EXAMPLE Get-AzServicePrincipalAadRoleAssignments #> Function Get-AzServicePrincipalAadRoleAssignments { [CmdletBinding()] Param ([Parameter(Mandatory = $true)][string]$ObjectId) If (!(Get-MgContext)) { Write-Warning "Please add an Azure AD connection to your current Azure session by executing Connect-AzAdReaderAccount."} $assignments = Get-MgRoleManagementDirectoryRoleAssignment -Filter "principalId eq `'$objectId`'" -All If ($assignments) { $assignments | % { Get-MgRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $_.RoleDefinitionId } } Else { Write-Warning "No Azure AD administrative role assignments found for $objectId" } } |