Skip to content

Instantly share code, notes, and snippets.

@andrewmatveychuk
Created February 24, 2024 21:12
Show Gist options
  • Save andrewmatveychuk/29064cb51f7c126698bbd121ecc0d404 to your computer and use it in GitHub Desktop.
Save andrewmatveychuk/29064cb51f7c126698bbd121ecc0d404 to your computer and use it in GitHub Desktop.
An improved Azure Automation runbook that sends custom logs to a Log Analytics workspace
#region LogEntry class definition
# Defining your custom categories using enum type
enum OperationResultList : byte {
Disabled
Deleted
Detected
}
# Defining your custom PowerShell class for log entries
class LogEntry {
[OperationResultList] $OperationResult
[ValidateNotNullOrEmpty()] [string] $OperationDetails
# Default constructor
LogEntry() { $this.Init(@{}) }
# Convenience constructor from hashtable
LogEntry([hashtable]$Properties) { $this.Init($Properties) }
# Common constructor for title and author
LogEntry([OperationResultList]$OperationResult, [string]$OperationDetails) {
$this.Init(@{OperationResult = $OperationResult; OperationDetails = $OperationDetails })
}
# Shared initializer method
hidden [void] Init([hashtable]$Properties) {
foreach ($Property in $Properties.Keys) {
$this.$Property = $Properties.$Property
}
}
}
#endregion
#region Creating your log entries
$logEntry1 = [LogEntry]@{
OperationResult = [OperationResultList]::Disabled # You can explicitly reference the enum type
OperationDetails = 'Some operation details goes here...'
}
$logEntry2 = [LogEntry]@{
OperationResult = 'Deleted' # Or you can just provide enum value as string
OperationDetails = 'Some operation details goes here...'
}
# Wrapping the log entries into an array, as the JSON payload expected by DCR should be a JSON array even for a single item
$logEntries = @($logEntry1, $logEntry2)
#endregion
#region Connecting to Azure
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process
# Connect to Azure with system-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity).context
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
#endregion
#region Pushing you logs
$Params = @{
DceEndpoint = Get-AutomationVariable -Name "dceEndpoint"
DcrImmutableId = Get-AutomationVariable -Name "dcrImmutableId"
StreamName = "Custom-Runbook1Operations_CL"
JsonPayload = $logEntries | ConvertTo-Json -AsArray -Compress -EnumsAsStrings # You need to provide the EnumsAsStrings parameter so your enum values are replaced with actual strings
Token = (Get-AzAccessToken -ResourceUrl "https://monitor.azure.com/").Token | ConvertTo-SecureString -AsPlainText -Force
}
New-LogEntry @Params
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment