Skip to content

Instantly share code, notes, and snippets.

Last active February 7, 2024 02:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save santisq/60f206833cfd385e8a65d21a5613723b to your computer and use it in GitHub Desktop.

Setup new Azure Data Explorer Table from MyAADLogs

This document details the steps needed to create a new Azure Data Explorer table for ingested logs from Azure Active Directory.

All ingested logs from AAD are written to a table in ADX named MyAADLogs, this table is overwritten over and over thus the need to create a parsing function which is used to filter the new ingested logs by their category and construct new records out of it to then write them to their corresponding tables.

Query MyAADLogs Table

First step is to query the MyAADLogs table filtering by the record.category property and expanding those properties of interest from each record. We can query the same logs using Log Analytics for comparison. For example, for NonInteractiveUserSignInLogs:

| mv-expand record = data.records
| where tostring(record.category) == 'NonInteractiveUserSignInLogs'
| extend LocationDetails = todynamic(['location'])
| project
    TimeGenerated = todatetime(record.['time']),
    OperationName = record.['operationName'],
    OperationVersion = record.['operationVersion'],
    Category = record.['category'],
    ResultType = record.['resultType'],
    ResultSignature = record.['resultSignature'],
    ResultDescription = record.['resultDescription'],
    DurationMs = record.['durationMs'],
    CorrelationId = record.['correlationId'],
    ResourceGroup = split(record.['resourceId'], '/')[-1],
    Identity = record.['identity'],
    Location = LocationDetails['countryOrRegion'],
    AppDisplayName =['appDisplayName'],
    AppId =['appId'],
    AuthenticationContextClassReferences =['authenticationContextClassReferences'],
    AuthenticationDetails =['authenticationDetails'],
    AuthenticationProcessingDetails =['authenticationProcessingDetails'],
    AuthenticationProtocol =['authenticationProtocol'],
    AuthenticationRequirement =['authenticationRequirement'],
    AuthenticationRequirementPolicies =['authenticationRequirementPolicies'],
    AutonomousSystemNumber =['autonomousSystemNumber'],
    ClientAppUsed =['clientAppUsed'],
    CreatedDateTime = todatetime(['createdDateTime']),
    CrossTenantAccessType =['crossTenantAccessType'],
    DeviceDetail =['deviceDetail'],
    HomeTenantId =['homeTenantId'],
    Id =['id'],
    IPAddress = record.callerIpAddress,
    IsInteractive =['isInteractive'],
    MfaDetail =['mfaDetail'],
    NetworkLocationDetails =['networkLocationDetails'],
    OriginalRequestId =['originalRequestId'],
    ProcessingTimeInMs =['processingTimeInMilliseconds'],
    ResourceDisplayName =['resourceDisplayName'],
    ResourceIdentity =['resourceId'],
    ResourceServicePrincipalId =['resourceServicePrincipalId'],
    ResourceTenantId =['resourceTenantId'],
    RiskDetail =['riskDetail'],
    RiskEventTypes =['riskEventTypes'],
    RiskLevelAggregated =['riskLevelAggregated'],
    RiskState =['riskState'],
    SessionLifetimePolicies =['sessionLifetimePolicies'],
    Status =['status'],
    TokenIssuerType =['tokenIssuerType'],
    UniqueTokenIdentifier =['uniqueTokenIdentifier'],
    UserAgent =['userAgent'],
    UserDisplayName =['userDisplayName'],
    UserId =['userId'],
    UserPrincipalName =['userPrincipalName'],
    UserType =['userType'],
    Type = 'AADNonInteractiveUserSignInLogs'

Create an ADX Function for the new query

Once we have the new query we can use the .create-or-alter function command to create a new Azure Data Explorer function. This command can also be used to update an existing query.

.create-or-alter function AADNonInteractiveUserSignInLogsParsing() {
    | mv-expand record = data.records
    | where tostring(record.category) == 'NonInteractiveUserSignInLogs'
    | project

After running the control command we should see the new function being created in the Functions table. Now we can re-use this function:

| take 1

Create the destination table

Next step is to create the table where the new logs are going to be written to. For this we can use the .set control command:

.set AADNonInteractiveUserSignInLogs <|
    | take 0

The | take 0 suffix is meant to make sure the command actually appends no records to the target table. We just need to create the schema for this new table.

Update the Table Policy

Last set is to change the table update policy, here we define which query is going to be used to update the table and the source table. For this we can use the .alter table policy update command:

.alter table AADNonInteractiveUserSignInLogs policy update
        "IsEnabled": true,
        "Source": "MyAADLogs",
        "Query": "AADNonInteractiveUserSignInLogsParsing",
        "IsTransactional": true,
        "PropagateIngestionProperties": false
# For more details see:
# Nuget Package:
# - net472 = PowerShell 5.1
# - net6.0 = PowerShell 7+
$assembly = Convert-Path .\\tools\net6.0\Kusto.Data.dll
try {
# NOTE: `Select-Object -Skip 1` is only needed if the CSV has headers,
# headers must be skipped for Csv ingestion.
$data = [System.IO.File]::ReadLines('path\to\csvToIngest.csv') |
Select-Object -Skip 1
$clusterUrl = ''
$databaseName = 'myDb'
$tableName = 'myTable'
$tenantId = 'xxxx-xxxx-xxxx-xxxx-xxxx'
# Do yourself a favor and use a Key Vault for this part :(
$adxClientId = 'xxxx-xxxx-xxxx-xxxx-xxxx'
$adxSecret = 's3cr3t'
$queryProvider = [Kusto.Data.Net.Client.KustoClientFactory]::CreateCslQueryProvider(
[Kusto.Data.KustoConnectionStringBuilder]::new($clusterUrl, $databaseName).
WithAadApplicationKeyAuthentication($adxClientId, $adxSecret, $tenantId))
$crp = [Kusto.Data.Common.ClientRequestProperties]::new()
$null = $queryProvider.ExecuteControlCommand(
".ingest inline into table {0} with (format = 'csv') <| {1}",
$tableName, [string]::Join([Environment]::NewLine, $data)), $crp)
finally {

Show the retention policy for a Table

.show table MyTable policy retention
| extend Policy = parse_json(Policy)
| extend SoftDeletePeriod = Policy.SoftDeletePeriod
| extend Recoverability = Policy.Recoverability
| project-away Policy, ChildEntities

Show ingestion failures on a Cluster

.show ingestion failures 
| where FailedOn > ago(30d)

Show principals assigned at Database level

.show database MyDatabase principals

Show principals assigned at Table level

Also lists the role assignment for each principal.

.show table MyTable principals

Get the schema of a Table

| getschema 

Ingest inline CSV data

.ingest inline into table MyTable with (format = 'csv') <|

Create a Table

.create table MyLogs(

Clear a Table

.clear table MyTable data 

Delete rows from a table based on a predicate

.delete table MyTable records <|
    | where // my predicate to delete rows

Grant a role assignment at Database level

  • Principals can be aadapp, aaduser, aadobject, etc.
  • ingestors is the role we're granting in the example, can also be admins, viewers, etc.
  • The syntax to add a principal 'aadapp=xxx-xxx-xxx-xxx-xxx;xxx-xxx-xxx-xxx-xxx' can be read as 'principalType=PrincipalGUID;TenantGUID'.
.add database MyDatabase ingestors (

Grant a role assignment at Table level

Very similar to previous example, with this we can grant permission to only a specific table.

10/17/2023: As of now, permissions added at Table level are not visible in the Portal UI.

.add table MyTable ingestors (

Copy a Table from one Cluster to other Cluster

.set MyDestinationTableName <|

Show an ADX Function Definition

.show function MyFunc
| project Body

Rename a Table Column

.rename column MyTable.MyColumn to MyNewColumnName

Delete Function

.drop function MyFunction

Delete Table

.drop table MyTable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment