Skip to content

Instantly share code, notes, and snippets.

@mmckechney
Created September 25, 2019 11:33
Show Gist options
  • Save mmckechney/dfd4511a86435e9ac79f2c8b260c3a58 to your computer and use it in GitHub Desktop.
Save mmckechney/dfd4511a86435e9ac79f2c8b260c3a58 to your computer and use it in GitHub Desktop.
Archive Azure Activity Logs for multiple subscriptions
<#
.SYNOPSIS
This script will configure EventHub logging for all Azure Activity logs in multiple subscriptions so that you can then archive the logs to another system
See: https://docs.microsoft.com/en-us/powershell/module/az.monitor/add-azlogprofile
.DESCRIPTION
Using an AAD account that has access to all of the subscriptions that you need to configure, this will loop through all of those
subscriptions, find all of the EventHub namespaces in those subscriptions and then find an EventHub that meets a specific naming format.
Once the proper EventHub is found, it will set the log profile for you
The naming format of the EventHub is up to you and can be edited on the "if($eventHub.Name ..." line #45
Alternatively, you could create a string array of EventHub names and look for a match in the loop
#>
#Login to Azure AD with an account that has access to all of the subscriptions that you need to configure
Login-AzAccount
#Pre-set variables
$logProfileName = "default"
$locations = (Get-AzLocation).Location
$locations += "global"
$sCtx
#Get the list of subscriptions that the login has access to
$subIds = (Get-AzSubscription).Id
#Loop through the subscriptions
foreach($subscriptionId in $subIds)
{
Write-Output "Subscription ID: $subscriptionId"
#Change subscription context and confirm the change...
while($sCtx.Subscription.Id -ne $subscriptionId)
{
$sCtx = Set-AzContext -Subscription "$subscriptionId" -Scope Process
}
#Get the EventHub namespaces for this subsciption
$eventHubNamespaces = Get-AzEventHubNamespace
#loop through all of the namespaces to find a matching EventHub
foreach($eventHub in $eventHubNamespaces)
{
if($eventHub.Name -match "<edit me!>") #EDIT THIS LINE to meet your naming match
{
#Set the Log profile to the EventHub
Write-Output "Found matching EventHub: $($eventHub.Name)"
$resourceGroupName = $eventHub.ResourceGroup
$serviceBusRuleId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.EventHub/namespaces/$($eventHub.Name)/authorizationrules/RootManageSharedAccessKey"
Add-AzLogProfile -Name $logProfileName -Location $locations -ServiceBusRuleId $serviceBusRuleId
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment