From 7050147f1be994175478956e27ae07f7c585266e Mon Sep 17 00:00:00 2001 From: angry-bender Date: Fri, 10 May 2024 11:39:50 +0930 Subject: [PATCH 1/7] Update Get-AzureADLogs.ps1 Fixed Interval field in AzureAdSignInLogs Acquisition Added the split by time feature to Get-AzureADAuditLogs, interval 12 hours (Larger dataset than SignInLogs). --- Scripts/Get-AzureADLogs.ps1 | 137 ++++++++++++++++++++++++++++-------- 1 file changed, 106 insertions(+), 31 deletions(-) diff --git a/Scripts/Get-AzureADLogs.ps1 b/Scripts/Get-AzureADLogs.ps1 index 37890a2..5e71f20 100644 --- a/Scripts/Get-AzureADLogs.ps1 +++ b/Scripts/Get-AzureADLogs.ps1 @@ -101,35 +101,35 @@ function Get-ADSignInLogs { [DateTime]$lastLog = $script:EndDate $currentDay = 0 - Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))" -Color "Green" + Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd")) is greather than $($script:EndDate.ToString("yyyy-MM-dd")) - are you sure you put in the correct year? Exiting!" -Color "Red" + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" return } while ($currentStart -lt $script:EndDate) { $currentEnd = $currentStart.AddMinutes($Interval) if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))." + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))." try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } catch{ Start-Sleep -Seconds 20 - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } } else { try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } catch{ Start-Sleep -Seconds 20 - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } } if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd")). Moving On!" + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")). Moving On!" } else { $currentCount = $results.Count @@ -140,9 +140,9 @@ function Get-ADSignInLogs { $currentTotal = $currentCount } - Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))" -Color "Green" + Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" - $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMdd"))-$($CurrentEnd.ToString("yyyyMMdd")).json" + $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." @@ -221,9 +221,11 @@ function Get-ADAuditLogs { param( [string]$startDate, [string]$endDate, - [string]$OutputDir, - [string]$UserIds, - [string]$Encoding + [string]$outputDir, + [string]$UserIds, + [switch]$MergeOutput, + [string]$Encoding, + [string]$Interval ) try { @@ -240,15 +242,23 @@ function Get-ADAuditLogs { Write-logFile -Message "[INFO] Running Get-ADAuditLogs" -Color "Green" + StartDateAz + EndDate + + if ($Interval -eq "") { + $Interval = 720 + Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440 (Larger values may result in out of memory errors)" + } + + $date = [datetime]::Now.ToString('yyyyMMddHHmmss') if ($OutputDir -eq "" ){ - $OutputDir = "Output\AzureAD" + $OutputDir = "Output\AzureAD\$date" if (!(test-path $OutputDir)) { - New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null write-logFile -Message "[INFO] Creating the following directory: $OutputDir" + New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null } } - else { if (Test-Path -Path $OutputDir) { write-LogFile -Message "[INFO] Custom directory set to: $OutputDir" @@ -260,29 +270,94 @@ function Get-ADAuditLogs { } } + + if ($UserIds){ + Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + } + + $filePath = "$OutputDir\$($date)-Auditlogs.json" - Write-logFile -Message "[INFO] Collecting the Directory Audit Logs" - if ($endDate -and $After) { - write-logFile -Message "[WARNING] Please provide only one of either a start date or end date" -Color "Red" + [DateTime]$currentStart = $script:StartDate + [DateTime]$currentEnd = $script:EndDate + [DateTime]$lastLog = $script:EndDate + $currentDay = 0 + + Write-LogFile -Message "[INFO] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" + if($currentStart -gt $script:EndDate){ + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" return } - $filter = "" - if ($endDate) { - $filter = "activityDateTime lt $endDate" - } - if ($startDate) { - $filter = "activityDateTime gt $startDate" + while ($currentStart -lt $script:EndDate) { + $currentEnd = $currentStart.AddMinutes($Interval) + Start-Sleep -Seconds 20 + if ($UserIds){ + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + catch{ + Start-Sleep -Seconds 20 + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + } + else { + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + catch{ + Start-Sleep -Seconds 20 + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + } + if ($null -eq $results -or $results.Count -eq 0) { + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")). Moving On!" + } + else { + $currentCount = $results.Count + if ($currentDay -ne 0){ + $currentTotal = $currentCount + $results.Count + } + else { + $currentTotal = $currentCount + } + + Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" + + $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding + + Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." + } + [Array]$results = @() + $CurrentStart = $CurrentEnd + $currentDay++ } + + if ($MergeOutput.IsPresent) + { + Write-LogFile -Message "[INFO] Merging output files into one file" + $outputDirMerged = "$OutputDir\Merged\" + If (!(test-path $outputDirMerged)) { + Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" + New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null + } + + $allJsonObjects = @() - if ($UserIds) { - if ($filter) { - $filter = " and $filter" + Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $jsonObjects = $content | ConvertFrom-Json + $allJsonObjects += $jsonObjects } - $results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' $filter" - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - } + + $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\AuditLogs-Combined.json" + } + + Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" +} else { $results = Get-AzureADAuditDirectoryLogs -All $true -Filter $filter $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding From 92ffd48c6b1a4b7f110c0035137f0f65331c29ac Mon Sep 17 00:00:00 2001 From: angry-bender Date: Fri, 10 May 2024 13:03:32 +0930 Subject: [PATCH 2/7] Update Get-AzureADLogs.ps1 FileName Issue --- Scripts/Get-AzureADLogs.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Scripts/Get-AzureADLogs.ps1 b/Scripts/Get-AzureADLogs.ps1 index 5e71f20..e57cb4d 100644 --- a/Scripts/Get-AzureADLogs.ps1 +++ b/Scripts/Get-AzureADLogs.ps1 @@ -326,7 +326,7 @@ function Get-ADAuditLogs { Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" - $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" + $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." From d01f1905c40c9651ddf048460bbc425ad4f84c26 Mon Sep 17 00:00:00 2001 From: angry-bender Date: Fri, 10 May 2024 15:26:04 +0930 Subject: [PATCH 3/7] Update Get-AzureADLogs.ps1 Added more verbose logging --- Scripts/Get-AzureADLogs.ps1 | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Scripts/Get-AzureADLogs.ps1 b/Scripts/Get-AzureADLogs.ps1 index e57cb4d..8ba8169 100644 --- a/Scripts/Get-AzureADLogs.ps1 +++ b/Scripts/Get-AzureADLogs.ps1 @@ -115,7 +115,9 @@ function Get-ADSignInLogs { [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } catch{ - Start-Sleep -Seconds 20 + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } } @@ -124,7 +126,9 @@ function Get-ADSignInLogs { [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } catch{ - Start-Sleep -Seconds 20 + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } } @@ -291,14 +295,16 @@ function Get-ADAuditLogs { while ($currentStart -lt $script:EndDate) { $currentEnd = $currentStart.AddMinutes($Interval) - Start-Sleep -Seconds 20 + Start-Sleep -Seconds 5 if ($UserIds){ Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." try{ [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } catch{ - Start-Sleep -Seconds 20 + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } } @@ -308,7 +314,9 @@ function Get-ADAuditLogs { [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } catch{ - Start-Sleep -Seconds 20 + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } } From ba073a948453425446abd029c34c787ad65b7635 Mon Sep 17 00:00:00 2001 From: angry-bender Date: Wed, 22 May 2024 11:43:26 +0930 Subject: [PATCH 4/7] Update Get-AzureADLogs.ps1 Fixed Date time formats --- Scripts/Get-AzureADLogs.ps1 | 662 ++++++++++++++++++------------------ 1 file changed, 326 insertions(+), 336 deletions(-) diff --git a/Scripts/Get-AzureADLogs.ps1 b/Scripts/Get-AzureADLogs.ps1 index 8ba8169..9ee8b70 100644 --- a/Scripts/Get-AzureADLogs.ps1 +++ b/Scripts/Get-AzureADLogs.ps1 @@ -1,374 +1,364 @@ # This contains functions for getting Azure AD logging function Get-ADSignInLogs { -<# - .SYNOPSIS - Get sign-in logs. - - .DESCRIPTION - The Get-ADSignInLogs cmdlet collects the contents of the Azure Active Directory sign-in logs. - The output will be written to: Output\AzureAD\SignInLogs.json - - .PARAMETER startDate - The startDate parameter specifies the date from which all logs need to be collected. - - .PARAMETER endDate - The Before parameter specifies the date endDate which all logs need to be collected. - - .PARAMETER OutputDir - OutputDir is the parameter specifying the output directory. - Default: Output\AzureAD - - .PARAMETER Encoding - Encoding is the parameter specifying the encoding of the JSON output file. - Default: UTF8 - - .PARAMETER MergeOutput - MergeOutput is the parameter specifying if you wish to merge outputs to a single file - Default: No - - .PARAMETER UserIds - UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - - .EXAMPLE - Get-ADSignInLogs - Get all sign-in logs. - - .EXAMPLE - Get-ADAuditLogs -UserIds Test@invictus-ir.com - Get sign-in logs for the user Test@invictus-ir.com. - - .EXAMPLE - Get-ADSignInLogs -endDate 2023-04-12 - Get sign-in logs before 2023-04-12. - - .EXAMPLE - Get-ADSignInLogs -startDate 2023-04-12 - Get sign-in logs after 2023-04-12. -#> - [CmdletBinding()] - param( - [string]$startDate, - [string]$endDate, - [string]$outputDir, - [string]$UserIds, - [switch]$MergeOutput, - [string]$Encoding, - [string]$Interval - ) - - try { - import-module AzureADPreview -force -ErrorAction stop - $areYouConnected = Get-AzureADAuditSignInLogs -ErrorAction stop - } - catch { - Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" - break - } - - Write-logFile -Message "[INFO] Running Get-AADSignInLogs" -Color "Green" - - StartDateAz - EndDate - - if ($Interval -eq "") { - $Interval = 1440 - Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440" - } - - if ($Encoding -eq "" ){ - $Encoding = "UTF8" - } - - $date = [datetime]::Now.ToString('yyyyMMddHHmmss') - if ($OutputDir -eq "" ){ - $OutputDir = "Output\AzureAD\$date" - if (!(test-path $OutputDir)) { - write-logFile -Message "[INFO] Creating the following directory: $OutputDir" - New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null - } - } - - if ($UserIds){ - Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" - } - - - $filePath = "$OutputDir\SignInLogs.json" + <# + .SYNOPSIS + Get sign-in logs. + + .DESCRIPTION + The Get-ADSignInLogs cmdlet collects the contents of the Azure Active Directory sign-in logs. + The output will be written to: Output\AzureAD\SignInLogs.json + + .PARAMETER startDate + The startDate parameter specifies the date from which all logs need to be collected. + + .PARAMETER endDate + The Before parameter specifies the date endDate which all logs need to be collected. + + .PARAMETER OutputDir + OutputDir is the parameter specifying the output directory. + Default: Output\AzureAD + + .PARAMETER Encoding + Encoding is the parameter specifying the encoding of the JSON output file. + Default: UTF8 + + .PARAMETER MergeOutput + MergeOutput is the parameter specifying if you wish to merge outputs to a single file + Default: No + + .PARAMETER UserIds + UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - [DateTime]$currentStart = $script:StartDate - [DateTime]$currentEnd = $script:EndDate - [DateTime]$lastLog = $script:EndDate - $currentDay = 0 - - Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" - if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" - return - } - - while ($currentStart -lt $script:EndDate) { - $currentEnd = $currentStart.AddMinutes($Interval) - if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))." - try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" - } + .EXAMPLE + Get-ADSignInLogs + Get all sign-in logs. + + .EXAMPLE + Get-ADAuditLogs -UserIds Test@invictus-ir.com + Get sign-in logs for the user Test@invictus-ir.com. + + .EXAMPLE + Get-ADSignInLogs -endDate 2023-04-12 + Get sign-in logs before 2023-04-12. + + .EXAMPLE + Get-ADSignInLogs -startDate 2023-04-12 + Get sign-in logs after 2023-04-12. + #> + [CmdletBinding()] + param( + [string]$startDate, + [string]$endDate, + [string]$outputDir, + [string]$UserIds, + [switch]$MergeOutput, + [string]$Encoding, + [string]$Interval + ) + + try { + import-module AzureADPreview -force -ErrorAction stop + $areYouConnected = Get-AzureADAuditSignInLogs -ErrorAction stop } - else { - try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" + catch { + Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" + break + } + + Write-logFile -Message "[INFO] Running Get-AADSignInLogs" -Color "Green" + + StartDateAz + EndDate + + if ($Interval -eq "") { + $Interval = 1440 + Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440" + } + + if ($Encoding -eq "" ){ + $Encoding = "UTF8" + } + + $date = [datetime]::Now.ToString('yyyyMMddHHmmss') + if ($OutputDir -eq "" ){ + $OutputDir = "Output\AzureAD\$date" + if (!(test-path $OutputDir)) { + write-logFile -Message "[INFO] Creating the following directory: $OutputDir" + New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null } } - if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")). Moving On!" + + if ($UserIds){ + Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + } + + + $filePath = "$OutputDir\SignInLogs.json" + + [DateTime]$currentStart = $script:StartDate + [DateTime]$currentEnd = $script:EndDate + [DateTime]$lastLog = $script:EndDate + $currentDay = 0 + + Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))" -Color "Green" + if($currentStart -gt $script:EndDate){ + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd")) is greather than $($script:EndDate.ToString("yyyy-MM-dd")) - are you sure you put in the correct year? Exiting!" -Color "Red" + return } - else { - $currentCount = $results.Count - if ($currentDay -ne 0){ - $currentTotal = $currentCount + $results.Count + + while ($currentStart -lt $script:EndDate) { + $currentEnd = $currentStart.AddMinutes($Interval) + if ($UserIds){ + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))." + try{ + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + } + catch{ + Start-Sleep -Seconds 20 + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + } } else { - $currentTotal = $currentCount + try{ + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + } + catch{ + Start-Sleep -Seconds 20 + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" + } } - - Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" + if ($null -eq $results -or $results.Count -eq 0) { + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd")). Moving On!" + } + else { + $currentCount = $results.Count + if ($currentDay -ne 0){ + $currentTotal = $currentCount + $results.Count + } + else { + $currentTotal = $currentCount + } - $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - - Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." - } - [Array]$results = @() - $CurrentStart = $CurrentEnd - $currentDay++ - } + Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))" -Color "Green" + + $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMdd"))-$($CurrentEnd.ToString("yyyyMMdd")).json" + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - if ($MergeOutput.IsPresent) - { - Write-LogFile -Message "[INFO] Merging output files into one file" - $outputDirMerged = "$OutputDir\Merged\" - If (!(test-path $outputDirMerged)) { - Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" - New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null - } - - $allJsonObjects = @() - - Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $jsonObjects = $content | ConvertFrom-Json - $allJsonObjects += $jsonObjects + Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." + } + [Array]$results = @() + $CurrentStart = $CurrentEnd + $currentDay++ } + + if ($MergeOutput.IsPresent) + { + Write-LogFile -Message "[INFO] Merging output files into one file" + $outputDirMerged = "$OutputDir\Merged\" + If (!(test-path $outputDirMerged)) { + Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" + New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null + } - $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\SignInLogs-Combined.json" - } + $allJsonObjects = @() - Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" -} - -function Get-ADAuditLogs { -<# - .SYNOPSIS - Get directory audit logs. - - .DESCRIPTION - The Get-ADAuditLogs cmdlet collects the contents of the Azure Active Directory Audit logs. - The output will be written to: "Output\AzureAD\Auditlogs.json - - .PARAMETER startDate - The startDate parameter specifies the date from which all logs need to be collected. - - .PARAMETER endDate - The endDate parameter specifies the date before which all logs need to be collected. - - .PARAMETER OutputDir - outputDir is the parameter specifying the output directory. - Default: Output\AzureAD - - .PARAMETER Encoding - Encoding is the parameter specifying the encoding of the JSON output file. - Default: UTF8 - - .PARAMETER UserIds - UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - - .EXAMPLE - Get-ADAuditLogs - Get directory audit logs. - - .EXAMPLE - Get-ADAuditLogs -UserIds Test@invictus-ir.com - Get directory audit logs for the user Test@invictus-ir.com. - - .EXAMPLE - Get-ADAuditLogs -endDate 2023-04-12 - Get directory audit logs before 2023-04-12. - - .EXAMPLE - Get-ADAuditLogs -startDate 2023-04-12 - Get directory audit logs after 2023-04-12. -#> - [CmdletBinding()] - param( - [string]$startDate, - [string]$endDate, - [string]$outputDir, - [string]$UserIds, - [switch]$MergeOutput, - [string]$Encoding, - [string]$Interval - ) - - try { - $areYouConnected = Get-AzureADAuditDirectoryLogs -ErrorAction stop - } - catch { - Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" - break - } - - if ($Encoding -eq "" ){ - $Encoding = "UTF8" + Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $jsonObjects = $content | ConvertFrom-Json + $allJsonObjects += $jsonObjects + } + + $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\SignInLogs-Combined.json" + } + + Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" } - - Write-logFile -Message "[INFO] Running Get-ADAuditLogs" -Color "Green" - StartDateAz - EndDate - - if ($Interval -eq "") { - $Interval = 720 - Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440 (Larger values may result in out of memory errors)" - } - - - $date = [datetime]::Now.ToString('yyyyMMddHHmmss') - if ($OutputDir -eq "" ){ - $OutputDir = "Output\AzureAD\$date" - if (!(test-path $OutputDir)) { - write-logFile -Message "[INFO] Creating the following directory: $OutputDir" - New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null + function Get-ADAuditLogs { + <# + .SYNOPSIS + Get directory audit logs. + + .DESCRIPTION + The Get-ADAuditLogs cmdlet collects the contents of the Azure Active Directory Audit logs. + The output will be written to: "Output\AzureAD\Auditlogs.json + + .PARAMETER startDate + The startDate parameter specifies the date from which all logs need to be collected. + + .PARAMETER endDate + The endDate parameter specifies the date before which all logs need to be collected. + + .PARAMETER OutputDir + outputDir is the parameter specifying the output directory. + Default: Output\AzureAD + + .PARAMETER Encoding + Encoding is the parameter specifying the encoding of the JSON output file. + Default: UTF8 + + .PARAMETER UserIds + UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. + + .EXAMPLE + Get-ADAuditLogs + Get directory audit logs. + + .EXAMPLE + Get-ADAuditLogs -UserIds Test@invictus-ir.com + Get directory audit logs for the user Test@invictus-ir.com. + + .EXAMPLE + Get-ADAuditLogs -endDate 2023-04-12 + Get directory audit logs before 2023-04-12. + + .EXAMPLE + Get-ADAuditLogs -startDate 2023-04-12 + Get directory audit logs after 2023-04-12. + #> + [CmdletBinding()] + param( + [string]$startDate, + [string]$endDate, + [string]$outputDir, + [string]$UserIds, + [switch]$MergeOutput, + [string]$Encoding, + [string]$Interval + ) + + try { + $areYouConnected = Get-AzureADAuditDirectoryLogs -ErrorAction stop } - } - else { - if (Test-Path -Path $OutputDir) { - write-LogFile -Message "[INFO] Custom directory set to: $OutputDir" + catch { + Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" + break } - else { - write-Error "[Error] Custom directory invalid: $OutputDir exiting script" -ErrorAction Stop - write-LogFile -Message "[Error] Custom directory invalid: $OutputDir exiting script" + if ($Encoding -eq "" ){ + $Encoding = "UTF8" } - } - - - if ($UserIds){ - Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" - } - - - $filePath = "$OutputDir\$($date)-Auditlogs.json" - - [DateTime]$currentStart = $script:StartDate - [DateTime]$currentEnd = $script:EndDate - [DateTime]$lastLog = $script:EndDate - $currentDay = 0 - - Write-LogFile -Message "[INFO] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" - if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" - return - } - - while ($currentStart -lt $script:EndDate) { - $currentEnd = $currentStart.AddMinutes($Interval) - Start-Sleep -Seconds 5 - if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." - try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + + Write-logFile -Message "[INFO] Running Get-ADAuditLogs" -Color "Green" + + StartDateAz + EndDate + + if ($Interval -eq "") { + $Interval = 720 + Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440 (Larger values may result in out of memory errors)" + } + + + $date = [datetime]::Now.ToString('yyyyMMddHHmmss') + if ($OutputDir -eq "" ){ + $OutputDir = "Output\AzureAD\$date" + if (!(test-path $OutputDir)) { + write-logFile -Message "[INFO] Creating the following directory: $OutputDir" + New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null } } else { - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." - try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + if (Test-Path -Path $OutputDir) { + write-LogFile -Message "[INFO] Custom directory set to: $OutputDir" } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + + else { + write-Error "[Error] Custom directory invalid: $OutputDir exiting script" -ErrorAction Stop + write-LogFile -Message "[Error] Custom directory invalid: $OutputDir exiting script" } } - if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")). Moving On!" + + + if ($UserIds){ + Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + } + + + $filePath = "$OutputDir\$($date)-Auditlogs.json" + + [DateTime]$currentStart = $script:StartDate + [DateTime]$currentEnd = $script:EndDate + [DateTime]$lastLog = $script:EndDate + $currentDay = 0 + + Write-LogFile -Message "[INFO V6] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" + if($currentStart -gt $script:EndDate){ + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ")) is greather than $($script:EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ")) - are you sure you put in the correct year? Exiting!" -Color "Red" + return } - else { - $currentCount = $results.Count - if ($currentDay -ne 0){ - $currentTotal = $currentCount + $results.Count + + while ($currentStart -lt $script:EndDate) { + $currentEnd = $currentStart.AddMinutes($Interval) + Start-Sleep -Seconds 5 + if ($UserIds){ + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } } else { - $currentTotal = $currentCount + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } } - - Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" + if ($null -eq $results -or $results.Count -eq 0) { + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Moving On!" -Color "Yellow" + } + else { + $currentCount = $results.Count + if ($currentDay -ne 0){ + $currentTotal = $currentCount + $results.Count + } + else { + $currentTotal = $currentCount + } - $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - - Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." - } - [Array]$results = @() - $CurrentStart = $CurrentEnd - $currentDay++ - } + Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" + + $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - if ($MergeOutput.IsPresent) - { - Write-LogFile -Message "[INFO] Merging output files into one file" - $outputDirMerged = "$OutputDir\Merged\" - If (!(test-path $outputDirMerged)) { - Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" - New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null - } - - $allJsonObjects = @() - - Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $jsonObjects = $content | ConvertFrom-Json - $allJsonObjects += $jsonObjects + Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." + } + [Array]$results = @() + $CurrentStart = $CurrentEnd + $currentDay++ } + + if ($MergeOutput.IsPresent) + { + Write-LogFile -Message "[INFO] Merging output files into one file" + $outputDirMerged = "$OutputDir\Merged\" + If (!(test-path $outputDirMerged)) { + Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" + New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null + } - $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\AuditLogs-Combined.json" - } + $allJsonObjects = @() - Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" -} - else { - $results = Get-AzureADAuditDirectoryLogs -All $true -Filter $filter - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding + Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $jsonObjects = $content | ConvertFrom-Json + $allJsonObjects += $jsonObjects + } + + $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\AuditLogs-Combined.json" + } + + Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" } - Write-logFile -Message "[INFO] Directory audit logs written to $filePath" -Color "Green" -} From 7d566d5b45cfdfe2e059fff617cb37865fe1889b Mon Sep 17 00:00:00 2001 From: angry-bender Date: Wed, 22 May 2024 12:07:23 +0930 Subject: [PATCH 5/7] Revert "Update Get-AzureADLogs.ps1" This reverts commit ba073a948453425446abd029c34c787ad65b7635. --- Scripts/Get-AzureADLogs.ps1 | 662 ++++++++++++++++++------------------ 1 file changed, 336 insertions(+), 326 deletions(-) diff --git a/Scripts/Get-AzureADLogs.ps1 b/Scripts/Get-AzureADLogs.ps1 index 9ee8b70..8ba8169 100644 --- a/Scripts/Get-AzureADLogs.ps1 +++ b/Scripts/Get-AzureADLogs.ps1 @@ -1,364 +1,374 @@ # This contains functions for getting Azure AD logging function Get-ADSignInLogs { - <# - .SYNOPSIS - Get sign-in logs. - - .DESCRIPTION - The Get-ADSignInLogs cmdlet collects the contents of the Azure Active Directory sign-in logs. - The output will be written to: Output\AzureAD\SignInLogs.json - - .PARAMETER startDate - The startDate parameter specifies the date from which all logs need to be collected. - - .PARAMETER endDate - The Before parameter specifies the date endDate which all logs need to be collected. - - .PARAMETER OutputDir - OutputDir is the parameter specifying the output directory. - Default: Output\AzureAD - - .PARAMETER Encoding - Encoding is the parameter specifying the encoding of the JSON output file. - Default: UTF8 - - .PARAMETER MergeOutput - MergeOutput is the parameter specifying if you wish to merge outputs to a single file - Default: No - - .PARAMETER UserIds - UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - - .EXAMPLE - Get-ADSignInLogs - Get all sign-in logs. - - .EXAMPLE - Get-ADAuditLogs -UserIds Test@invictus-ir.com - Get sign-in logs for the user Test@invictus-ir.com. - - .EXAMPLE - Get-ADSignInLogs -endDate 2023-04-12 - Get sign-in logs before 2023-04-12. - - .EXAMPLE - Get-ADSignInLogs -startDate 2023-04-12 - Get sign-in logs after 2023-04-12. - #> - [CmdletBinding()] - param( - [string]$startDate, - [string]$endDate, - [string]$outputDir, - [string]$UserIds, - [switch]$MergeOutput, - [string]$Encoding, - [string]$Interval - ) - - try { - import-module AzureADPreview -force -ErrorAction stop - $areYouConnected = Get-AzureADAuditSignInLogs -ErrorAction stop - } - catch { - Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" - break - } - - Write-logFile -Message "[INFO] Running Get-AADSignInLogs" -Color "Green" - - StartDateAz - EndDate - - if ($Interval -eq "") { - $Interval = 1440 - Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440" - } - - if ($Encoding -eq "" ){ - $Encoding = "UTF8" +<# + .SYNOPSIS + Get sign-in logs. + + .DESCRIPTION + The Get-ADSignInLogs cmdlet collects the contents of the Azure Active Directory sign-in logs. + The output will be written to: Output\AzureAD\SignInLogs.json + + .PARAMETER startDate + The startDate parameter specifies the date from which all logs need to be collected. + + .PARAMETER endDate + The Before parameter specifies the date endDate which all logs need to be collected. + + .PARAMETER OutputDir + OutputDir is the parameter specifying the output directory. + Default: Output\AzureAD + + .PARAMETER Encoding + Encoding is the parameter specifying the encoding of the JSON output file. + Default: UTF8 + + .PARAMETER MergeOutput + MergeOutput is the parameter specifying if you wish to merge outputs to a single file + Default: No + + .PARAMETER UserIds + UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. + + .EXAMPLE + Get-ADSignInLogs + Get all sign-in logs. + + .EXAMPLE + Get-ADAuditLogs -UserIds Test@invictus-ir.com + Get sign-in logs for the user Test@invictus-ir.com. + + .EXAMPLE + Get-ADSignInLogs -endDate 2023-04-12 + Get sign-in logs before 2023-04-12. + + .EXAMPLE + Get-ADSignInLogs -startDate 2023-04-12 + Get sign-in logs after 2023-04-12. +#> + [CmdletBinding()] + param( + [string]$startDate, + [string]$endDate, + [string]$outputDir, + [string]$UserIds, + [switch]$MergeOutput, + [string]$Encoding, + [string]$Interval + ) + + try { + import-module AzureADPreview -force -ErrorAction stop + $areYouConnected = Get-AzureADAuditSignInLogs -ErrorAction stop + } + catch { + Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" + break + } + + Write-logFile -Message "[INFO] Running Get-AADSignInLogs" -Color "Green" + + StartDateAz + EndDate + + if ($Interval -eq "") { + $Interval = 1440 + Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440" + } + + if ($Encoding -eq "" ){ + $Encoding = "UTF8" + } + + $date = [datetime]::Now.ToString('yyyyMMddHHmmss') + if ($OutputDir -eq "" ){ + $OutputDir = "Output\AzureAD\$date" + if (!(test-path $OutputDir)) { + write-logFile -Message "[INFO] Creating the following directory: $OutputDir" + New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null } - - $date = [datetime]::Now.ToString('yyyyMMddHHmmss') - if ($OutputDir -eq "" ){ - $OutputDir = "Output\AzureAD\$date" - if (!(test-path $OutputDir)) { - write-logFile -Message "[INFO] Creating the following directory: $OutputDir" - New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null + } + + if ($UserIds){ + Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + } + + + $filePath = "$OutputDir\SignInLogs.json" + + [DateTime]$currentStart = $script:StartDate + [DateTime]$currentEnd = $script:EndDate + [DateTime]$lastLog = $script:EndDate + $currentDay = 0 + + Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" + if($currentStart -gt $script:EndDate){ + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" + return + } + + while ($currentStart -lt $script:EndDate) { + $currentEnd = $currentStart.AddMinutes($Interval) + if ($UserIds){ + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))." + try{ + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" + } + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" } } - - if ($UserIds){ - Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + else { + try{ + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" + } + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" + } } - - - $filePath = "$OutputDir\SignInLogs.json" - - [DateTime]$currentStart = $script:StartDate - [DateTime]$currentEnd = $script:EndDate - [DateTime]$lastLog = $script:EndDate - $currentDay = 0 - - Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))" -Color "Green" - if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd")) is greather than $($script:EndDate.ToString("yyyy-MM-dd")) - are you sure you put in the correct year? Exiting!" -Color "Red" - return + if ($null -eq $results -or $results.Count -eq 0) { + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")). Moving On!" } - - while ($currentStart -lt $script:EndDate) { - $currentEnd = $currentStart.AddMinutes($Interval) - if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))." - try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" - } - catch{ - Start-Sleep -Seconds 20 - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" - } + else { + $currentCount = $results.Count + if ($currentDay -ne 0){ + $currentTotal = $currentCount + $results.Count } else { - try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" - } - catch{ - Start-Sleep -Seconds 20 - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd"))" - } + $currentTotal = $currentCount } - if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd")). Moving On!" - } - else { - $currentCount = $results.Count - if ($currentDay -ne 0){ - $currentTotal = $currentCount + $results.Count - } - else { - $currentTotal = $currentCount - } + + Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" - Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd"))" -Color "Green" - - $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMdd"))-$($CurrentEnd.ToString("yyyyMMdd")).json" - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - - Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." - } - [Array]$results = @() - $CurrentStart = $CurrentEnd - $currentDay++ - } - - if ($MergeOutput.IsPresent) - { - Write-LogFile -Message "[INFO] Merging output files into one file" - $outputDirMerged = "$OutputDir\Merged\" - If (!(test-path $outputDirMerged)) { - Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" - New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null - } - - $allJsonObjects = @() - - Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $jsonObjects = $content | ConvertFrom-Json - $allJsonObjects += $jsonObjects - } - - $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\SignInLogs-Combined.json" + $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding + + Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." } - - Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" + [Array]$results = @() + $CurrentStart = $CurrentEnd + $currentDay++ } - function Get-ADAuditLogs { - <# - .SYNOPSIS - Get directory audit logs. - - .DESCRIPTION - The Get-ADAuditLogs cmdlet collects the contents of the Azure Active Directory Audit logs. - The output will be written to: "Output\AzureAD\Auditlogs.json - - .PARAMETER startDate - The startDate parameter specifies the date from which all logs need to be collected. - - .PARAMETER endDate - The endDate parameter specifies the date before which all logs need to be collected. - - .PARAMETER OutputDir - outputDir is the parameter specifying the output directory. - Default: Output\AzureAD - - .PARAMETER Encoding - Encoding is the parameter specifying the encoding of the JSON output file. - Default: UTF8 - - .PARAMETER UserIds - UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - - .EXAMPLE - Get-ADAuditLogs - Get directory audit logs. - - .EXAMPLE - Get-ADAuditLogs -UserIds Test@invictus-ir.com - Get directory audit logs for the user Test@invictus-ir.com. + if ($MergeOutput.IsPresent) + { + Write-LogFile -Message "[INFO] Merging output files into one file" + $outputDirMerged = "$OutputDir\Merged\" + If (!(test-path $outputDirMerged)) { + Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" + New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null + } + + $allJsonObjects = @() + + Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $jsonObjects = $content | ConvertFrom-Json + $allJsonObjects += $jsonObjects + } - .EXAMPLE - Get-ADAuditLogs -endDate 2023-04-12 - Get directory audit logs before 2023-04-12. + $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\SignInLogs-Combined.json" + } - .EXAMPLE - Get-ADAuditLogs -startDate 2023-04-12 - Get directory audit logs after 2023-04-12. - #> - [CmdletBinding()] - param( - [string]$startDate, - [string]$endDate, - [string]$outputDir, - [string]$UserIds, - [switch]$MergeOutput, - [string]$Encoding, - [string]$Interval - ) + Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" +} + +function Get-ADAuditLogs { +<# + .SYNOPSIS + Get directory audit logs. + + .DESCRIPTION + The Get-ADAuditLogs cmdlet collects the contents of the Azure Active Directory Audit logs. + The output will be written to: "Output\AzureAD\Auditlogs.json + + .PARAMETER startDate + The startDate parameter specifies the date from which all logs need to be collected. + + .PARAMETER endDate + The endDate parameter specifies the date before which all logs need to be collected. + + .PARAMETER OutputDir + outputDir is the parameter specifying the output directory. + Default: Output\AzureAD + + .PARAMETER Encoding + Encoding is the parameter specifying the encoding of the JSON output file. + Default: UTF8 + + .PARAMETER UserIds + UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. + + .EXAMPLE + Get-ADAuditLogs + Get directory audit logs. + + .EXAMPLE + Get-ADAuditLogs -UserIds Test@invictus-ir.com + Get directory audit logs for the user Test@invictus-ir.com. + + .EXAMPLE + Get-ADAuditLogs -endDate 2023-04-12 + Get directory audit logs before 2023-04-12. + + .EXAMPLE + Get-ADAuditLogs -startDate 2023-04-12 + Get directory audit logs after 2023-04-12. +#> + [CmdletBinding()] + param( + [string]$startDate, + [string]$endDate, + [string]$outputDir, + [string]$UserIds, + [switch]$MergeOutput, + [string]$Encoding, + [string]$Interval + ) + + try { + $areYouConnected = Get-AzureADAuditDirectoryLogs -ErrorAction stop + } + catch { + Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" + break + } + + if ($Encoding -eq "" ){ + $Encoding = "UTF8" + } + + Write-logFile -Message "[INFO] Running Get-ADAuditLogs" -Color "Green" - try { - $areYouConnected = Get-AzureADAuditDirectoryLogs -ErrorAction stop - } - catch { - Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" - break + StartDateAz + EndDate + + if ($Interval -eq "") { + $Interval = 720 + Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440 (Larger values may result in out of memory errors)" + } + + + $date = [datetime]::Now.ToString('yyyyMMddHHmmss') + if ($OutputDir -eq "" ){ + $OutputDir = "Output\AzureAD\$date" + if (!(test-path $OutputDir)) { + write-logFile -Message "[INFO] Creating the following directory: $OutputDir" + New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null } - - if ($Encoding -eq "" ){ - $Encoding = "UTF8" + } + else { + if (Test-Path -Path $OutputDir) { + write-LogFile -Message "[INFO] Custom directory set to: $OutputDir" } - Write-logFile -Message "[INFO] Running Get-ADAuditLogs" -Color "Green" - - StartDateAz - EndDate - - if ($Interval -eq "") { - $Interval = 720 - Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440 (Larger values may result in out of memory errors)" + else { + write-Error "[Error] Custom directory invalid: $OutputDir exiting script" -ErrorAction Stop + write-LogFile -Message "[Error] Custom directory invalid: $OutputDir exiting script" } - - - $date = [datetime]::Now.ToString('yyyyMMddHHmmss') - if ($OutputDir -eq "" ){ - $OutputDir = "Output\AzureAD\$date" - if (!(test-path $OutputDir)) { - write-logFile -Message "[INFO] Creating the following directory: $OutputDir" - New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null + } + + + if ($UserIds){ + Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + } + + + $filePath = "$OutputDir\$($date)-Auditlogs.json" + + [DateTime]$currentStart = $script:StartDate + [DateTime]$currentEnd = $script:EndDate + [DateTime]$lastLog = $script:EndDate + $currentDay = 0 + + Write-LogFile -Message "[INFO] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" + if($currentStart -gt $script:EndDate){ + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" + return + } + + while ($currentStart -lt $script:EndDate) { + $currentEnd = $currentStart.AddMinutes($Interval) + Start-Sleep -Seconds 5 + if ($UserIds){ + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } } else { - if (Test-Path -Path $OutputDir) { - write-LogFile -Message "[INFO] Custom directory set to: $OutputDir" + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } - - else { - write-Error "[Error] Custom directory invalid: $OutputDir exiting script" -ErrorAction Stop - write-LogFile -Message "[Error] Custom directory invalid: $OutputDir exiting script" + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } } - - - if ($UserIds){ - Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" - } - - - $filePath = "$OutputDir\$($date)-Auditlogs.json" - - [DateTime]$currentStart = $script:StartDate - [DateTime]$currentEnd = $script:EndDate - [DateTime]$lastLog = $script:EndDate - $currentDay = 0 - - Write-LogFile -Message "[INFO V6] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" - if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ")) is greather than $($script:EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ")) - are you sure you put in the correct year? Exiting!" -Color "Red" - return + if ($null -eq $results -or $results.Count -eq 0) { + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")). Moving On!" } - - while ($currentStart -lt $script:EndDate) { - $currentEnd = $currentStart.AddMinutes($Interval) - Start-Sleep -Seconds 5 - if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails - } + else { + $currentCount = $results.Count + if ($currentDay -ne 0){ + $currentTotal = $currentCount + $results.Count } else { - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails - } + $currentTotal = $currentCount } - if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Moving On!" -Color "Yellow" - } - else { - $currentCount = $results.Count - if ($currentDay -ne 0){ - $currentTotal = $currentCount + $results.Count - } - else { - $currentTotal = $currentCount - } + + Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" - Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" - - $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding + $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding + + Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." + } + [Array]$results = @() + $CurrentStart = $CurrentEnd + $currentDay++ + } - Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." - } - [Array]$results = @() - $CurrentStart = $CurrentEnd - $currentDay++ + if ($MergeOutput.IsPresent) + { + Write-LogFile -Message "[INFO] Merging output files into one file" + $outputDirMerged = "$OutputDir\Merged\" + If (!(test-path $outputDirMerged)) { + Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" + New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null + } + + $allJsonObjects = @() + + Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $jsonObjects = $content | ConvertFrom-Json + $allJsonObjects += $jsonObjects } - - if ($MergeOutput.IsPresent) - { - Write-LogFile -Message "[INFO] Merging output files into one file" - $outputDirMerged = "$OutputDir\Merged\" - If (!(test-path $outputDirMerged)) { - Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" - New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null - } - $allJsonObjects = @() + $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\AuditLogs-Combined.json" + } - Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $jsonObjects = $content | ConvertFrom-Json - $allJsonObjects += $jsonObjects - } - - $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\AuditLogs-Combined.json" - } - - Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" + Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" +} + else { + $results = Get-AzureADAuditDirectoryLogs -All $true -Filter $filter + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding } + Write-logFile -Message "[INFO] Directory audit logs written to $filePath" -Color "Green" +} From 673538a341e65945547dd36df4613e4c5bb2b510 Mon Sep 17 00:00:00 2001 From: angry-bender Date: Wed, 22 May 2024 12:17:51 +0930 Subject: [PATCH 6/7] Added extra timestamps to Get-ADSignInLogs, Fixed broken timestamps in Get Audit Logs --- Scripts/Get-AzureADLogs.ps1 | 668 ++++++++++++++++++------------------ 1 file changed, 331 insertions(+), 337 deletions(-) diff --git a/Scripts/Get-AzureADLogs.ps1 b/Scripts/Get-AzureADLogs.ps1 index 8ba8169..5f018f7 100644 --- a/Scripts/Get-AzureADLogs.ps1 +++ b/Scripts/Get-AzureADLogs.ps1 @@ -1,374 +1,368 @@ # This contains functions for getting Azure AD logging function Get-ADSignInLogs { -<# - .SYNOPSIS - Get sign-in logs. - - .DESCRIPTION - The Get-ADSignInLogs cmdlet collects the contents of the Azure Active Directory sign-in logs. - The output will be written to: Output\AzureAD\SignInLogs.json - - .PARAMETER startDate - The startDate parameter specifies the date from which all logs need to be collected. - - .PARAMETER endDate - The Before parameter specifies the date endDate which all logs need to be collected. - - .PARAMETER OutputDir - OutputDir is the parameter specifying the output directory. - Default: Output\AzureAD - - .PARAMETER Encoding - Encoding is the parameter specifying the encoding of the JSON output file. - Default: UTF8 - - .PARAMETER MergeOutput - MergeOutput is the parameter specifying if you wish to merge outputs to a single file - Default: No - - .PARAMETER UserIds - UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - - .EXAMPLE - Get-ADSignInLogs - Get all sign-in logs. - - .EXAMPLE - Get-ADAuditLogs -UserIds Test@invictus-ir.com - Get sign-in logs for the user Test@invictus-ir.com. - - .EXAMPLE - Get-ADSignInLogs -endDate 2023-04-12 - Get sign-in logs before 2023-04-12. - - .EXAMPLE - Get-ADSignInLogs -startDate 2023-04-12 - Get sign-in logs after 2023-04-12. -#> - [CmdletBinding()] - param( - [string]$startDate, - [string]$endDate, - [string]$outputDir, - [string]$UserIds, - [switch]$MergeOutput, - [string]$Encoding, - [string]$Interval - ) - - try { - import-module AzureADPreview -force -ErrorAction stop - $areYouConnected = Get-AzureADAuditSignInLogs -ErrorAction stop - } - catch { - Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" - break - } - - Write-logFile -Message "[INFO] Running Get-AADSignInLogs" -Color "Green" - - StartDateAz - EndDate - - if ($Interval -eq "") { - $Interval = 1440 - Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440" - } - - if ($Encoding -eq "" ){ - $Encoding = "UTF8" - } - - $date = [datetime]::Now.ToString('yyyyMMddHHmmss') - if ($OutputDir -eq "" ){ - $OutputDir = "Output\AzureAD\$date" - if (!(test-path $OutputDir)) { - write-logFile -Message "[INFO] Creating the following directory: $OutputDir" - New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null - } - } - - if ($UserIds){ - Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" - } - - - $filePath = "$OutputDir\SignInLogs.json" + <# + .SYNOPSIS + Get sign-in logs. + + .DESCRIPTION + The Get-ADSignInLogs cmdlet collects the contents of the Azure Active Directory sign-in logs. + The output will be written to: Output\AzureAD\SignInLogs.json + + .PARAMETER startDate + The startDate parameter specifies the date from which all logs need to be collected. + + .PARAMETER endDate + The Before parameter specifies the date endDate which all logs need to be collected. + + .PARAMETER OutputDir + OutputDir is the parameter specifying the output directory. + Default: Output\AzureAD + + .PARAMETER Encoding + Encoding is the parameter specifying the encoding of the JSON output file. + Default: UTF8 + + .PARAMETER MergeOutput + MergeOutput is the parameter specifying if you wish to merge outputs to a single file + Default: No + + .PARAMETER UserIds + UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - [DateTime]$currentStart = $script:StartDate - [DateTime]$currentEnd = $script:EndDate - [DateTime]$lastLog = $script:EndDate - $currentDay = 0 - - Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" - if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" - return - } - - while ($currentStart -lt $script:EndDate) { - $currentEnd = $currentStart.AddMinutes($Interval) - if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))." - try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" - } + .EXAMPLE + Get-ADSignInLogs + Get all sign-in logs. + + .EXAMPLE + Get-ADAuditLogs -UserIds Test@invictus-ir.com + Get sign-in logs for the user Test@invictus-ir.com. + + .EXAMPLE + Get-ADSignInLogs -endDate 2023-04-12 + Get sign-in logs before 2023-04-12. + + .EXAMPLE + Get-ADSignInLogs -startDate 2023-04-12 + Get sign-in logs after 2023-04-12. + #> + [CmdletBinding()] + param( + [string]$startDate, + [string]$endDate, + [string]$outputDir, + [string]$UserIds, + [switch]$MergeOutput, + [string]$Encoding, + [string]$Interval + ) + + try { + import-module AzureADPreview -force -ErrorAction stop + $areYouConnected = Get-AzureADAuditSignInLogs -ErrorAction stop } - else { - try{ - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-dd HH:mm:ss")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-dd HH:mm:ss"))" + catch { + Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" + break + } + + Write-logFile -Message "[INFO] Running Get-AADSignInLogs" -Color "Green" + + StartDateAz + EndDate + + if ($Interval -eq "") { + $Interval = 1440 + Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440" + } + + if ($Encoding -eq "" ){ + $Encoding = "UTF8" + } + + $date = [datetime]::Now.ToString('yyyyMMddHHmmss') + if ($OutputDir -eq "" ){ + $OutputDir = "Output\AzureAD\$date" + if (!(test-path $OutputDir)) { + write-logFile -Message "[INFO] Creating the following directory: $OutputDir" + New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null } } - if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")). Moving On!" + + if ($UserIds){ + Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + } + + + $filePath = "$OutputDir\SignInLogs.json" + + [DateTime]$currentStart = $script:StartDate + [DateTime]$currentEnd = $script:EndDate + [DateTime]$lastLog = $script:EndDate + $currentDay = 0 + + Write-LogFile -Message "[INFO] Extracting all available Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" + if($currentStart -gt $script:EndDate){ + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ")) is greather than $($script:EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ")) - are you sure you put in the correct year? Exiting!" -Color "Red" + return } - else { - $currentCount = $results.Count - if ($currentDay -ne 0){ - $currentTotal = $currentCount + $results.Count + + while ($currentStart -lt $script:EndDate) { + $currentEnd = $currentStart.AddMinutes($Interval) + if ($UserIds){ + Write-LogFile -Message "[INFO] Collecting Directory Sign-in logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + try{ + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-ddTHH:mm:ssZ")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ"))" + } + catch{ + Start-Sleep -Seconds 20 + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "UserPrincipalName eq '$($Userids)' and createdDateTime lt $($currentEnd.ToString("yyyy-MM-ddTHH:mm:ssZ")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ"))" + } } else { - $currentTotal = $currentCount + try{ + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-ddTHH:mm:ssZ")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ"))" + } + catch{ + Start-Sleep -Seconds 20 + [Array]$results = Get-AzureADAuditSignInLogs -All $true -Filter "createdDateTime lt $($currentEnd.ToString("yyyy-MM-ddTHH:mm:ssZ")) and createdDateTime gt $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ"))" + } } - - Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))" -Color "Green" + if ($null -eq $results -or $results.Count -eq 0) { + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Moving On!" + } + else { + $currentCount = $results.Count + if ($currentDay -ne 0){ + $currentTotal = $currentCount + $results.Count + } + else { + $currentTotal = $currentCount + } - $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - - Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." - } - [Array]$results = @() - $CurrentStart = $CurrentEnd - $currentDay++ - } + Write-LogFile -Message "[INFO] Found $currentCount Directory Sign-in Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" + + $filePath = "$OutputDir\SignInLogs-$($CurrentStart.ToString("yyyyMMdd"))-$($CurrentEnd.ToString("yyyyMMdd")).json" + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - if ($MergeOutput.IsPresent) - { - Write-LogFile -Message "[INFO] Merging output files into one file" - $outputDirMerged = "$OutputDir\Merged\" - If (!(test-path $outputDirMerged)) { - Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" - New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null - } - - $allJsonObjects = @() - - Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $jsonObjects = $content | ConvertFrom-Json - $allJsonObjects += $jsonObjects + Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." + } + [Array]$results = @() + $CurrentStart = $CurrentEnd + $currentDay++ } + + if ($MergeOutput.IsPresent) + { + Write-LogFile -Message "[INFO] Merging output files into one file" + $outputDirMerged = "$OutputDir\Merged\" + If (!(test-path $outputDirMerged)) { + Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" + New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null + } - $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\SignInLogs-Combined.json" - } + $allJsonObjects = @() - Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" -} - -function Get-ADAuditLogs { -<# - .SYNOPSIS - Get directory audit logs. - - .DESCRIPTION - The Get-ADAuditLogs cmdlet collects the contents of the Azure Active Directory Audit logs. - The output will be written to: "Output\AzureAD\Auditlogs.json - - .PARAMETER startDate - The startDate parameter specifies the date from which all logs need to be collected. - - .PARAMETER endDate - The endDate parameter specifies the date before which all logs need to be collected. - - .PARAMETER OutputDir - outputDir is the parameter specifying the output directory. - Default: Output\AzureAD - - .PARAMETER Encoding - Encoding is the parameter specifying the encoding of the JSON output file. - Default: UTF8 - - .PARAMETER UserIds - UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. - - .EXAMPLE - Get-ADAuditLogs - Get directory audit logs. - - .EXAMPLE - Get-ADAuditLogs -UserIds Test@invictus-ir.com - Get directory audit logs for the user Test@invictus-ir.com. - - .EXAMPLE - Get-ADAuditLogs -endDate 2023-04-12 - Get directory audit logs before 2023-04-12. - - .EXAMPLE - Get-ADAuditLogs -startDate 2023-04-12 - Get directory audit logs after 2023-04-12. -#> - [CmdletBinding()] - param( - [string]$startDate, - [string]$endDate, - [string]$outputDir, - [string]$UserIds, - [switch]$MergeOutput, - [string]$Encoding, - [string]$Interval - ) - - try { - $areYouConnected = Get-AzureADAuditDirectoryLogs -ErrorAction stop - } - catch { - Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" - break - } - - if ($Encoding -eq "" ){ - $Encoding = "UTF8" + Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $jsonObjects = $content | ConvertFrom-Json + $allJsonObjects += $jsonObjects + } + + $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\SignInLogs-Combined.json" + } + + Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" } - - Write-logFile -Message "[INFO] Running Get-ADAuditLogs" -Color "Green" - StartDateAz - EndDate - - if ($Interval -eq "") { - $Interval = 720 - Write-LogFile -Message "[INFO] Setting the Interval to the default value of 1440 (Larger values may result in out of memory errors)" - } - - - $date = [datetime]::Now.ToString('yyyyMMddHHmmss') - if ($OutputDir -eq "" ){ - $OutputDir = "Output\AzureAD\$date" - if (!(test-path $OutputDir)) { - write-logFile -Message "[INFO] Creating the following directory: $OutputDir" - New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null + function Get-ADAuditLogs { + <# + .SYNOPSIS + Get directory audit logs. + + .DESCRIPTION + The Get-ADAuditLogs cmdlet collects the contents of the Azure Active Directory Audit logs. + The output will be written to: "Output\AzureAD\Auditlogs.json + + .PARAMETER startDate + The startDate parameter specifies the date from which all logs need to be collected. + + .PARAMETER endDate + The endDate parameter specifies the date before which all logs need to be collected. + + .PARAMETER OutputDir + outputDir is the parameter specifying the output directory. + Default: Output\AzureAD + + .PARAMETER Encoding + Encoding is the parameter specifying the encoding of the JSON output file. + Default: UTF8 + + .PARAMETER UserIds + UserIds is the UserIds parameter filtering the log entries by the account of the user who performed the actions. + + .EXAMPLE + Get-ADAuditLogs + Get directory audit logs. + + .EXAMPLE + Get-ADAuditLogs -UserIds Test@invictus-ir.com + Get directory audit logs for the user Test@invictus-ir.com. + + .EXAMPLE + Get-ADAuditLogs -endDate 2024-04-12T01:00:00Z + Get directory audit logs before 2023-04-12 at 01:00. + + .EXAMPLE + Get-ADAuditLogs -startDate 2024-04-12T01:00:00Z + Get directory audit logs after 2023-04-12 at 01:00. + + .EXAMPLE + Get-ADAuditLogs -startDate 2024-04-12T01:00:00Z -endDate 2024-04-12T02:00:00Z + Get directory audit logs after 2023-04-12 between 01:00 and 02:00 + #> + [CmdletBinding()] + param( + [string]$startDate, + [string]$endDate, + [string]$outputDir, + [string]$UserIds, + [switch]$MergeOutput, + [string]$Encoding, + [string]$Interval + ) + + try { + $areYouConnected = Get-AzureADAuditDirectoryLogs -ErrorAction stop } - } - else { - if (Test-Path -Path $OutputDir) { - write-LogFile -Message "[INFO] Custom directory set to: $OutputDir" + catch { + Write-logFile -Message "[WARNING] You must call Connect-Azure or install AzureADPreview before running this script" -Color "Red" + break } - else { - write-Error "[Error] Custom directory invalid: $OutputDir exiting script" -ErrorAction Stop - write-LogFile -Message "[Error] Custom directory invalid: $OutputDir exiting script" + if ($Encoding -eq "" ){ + $Encoding = "UTF8" } - } - - - if ($UserIds){ - Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" - } - - - $filePath = "$OutputDir\$($date)-Auditlogs.json" - - [DateTime]$currentStart = $script:StartDate - [DateTime]$currentEnd = $script:EndDate - [DateTime]$lastLog = $script:EndDate - $currentDay = 0 - - Write-LogFile -Message "[INFO] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" - if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) is greather than $($script:EndDate.ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) - are you sure you put in the correct year? Exiting!" -Color "Red" - return - } - - while ($currentStart -lt $script:EndDate) { - $currentEnd = $currentStart.AddMinutes($Interval) - Start-Sleep -Seconds 5 - if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." - try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails - } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + + Write-logFile -Message "[INFO] Running Get-ADAuditLogs" -Color "Green" + + StartDateAz + EndDate + + if ($Interval -eq "") { + $Interval = 720 + Write-LogFile -Message "[INFO] Setting the Interval to the default value of 720 (Larger values may result in out of memory errors)" + } + + + $date = [datetime]::Now.ToString('yyyyMMddHHmmss') + if ($OutputDir -eq "" ){ + $OutputDir = "Output\AzureAD\$date" + if (!(test-path $OutputDir)) { + write-logFile -Message "[INFO] Creating the following directory: $OutputDir" + New-Item -ItemType Directory -Force -Name $OutputDir | Out-Null } } else { - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))." - try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + if (Test-Path -Path $OutputDir) { + write-LogFile -Message "[INFO] Custom directory set to: $OutputDir" } - catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" - Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + + else { + write-Error "[Error] Custom directory invalid: $OutputDir exiting script" -ErrorAction Stop + write-LogFile -Message "[Error] Custom directory invalid: $OutputDir exiting script" } } - if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")). Moving On!" + + + if ($UserIds){ + Write-LogFile -Message "[INFO] UserID's eq $($UserIds)" + } + + + $filePath = "$OutputDir\$($date)-Auditlogs.json" + + [DateTime]$currentStart = $script:StartDate + [DateTime]$currentEnd = $script:EndDate + [DateTime]$lastLog = $script:EndDate + $currentDay = 0 + + Write-LogFile -Message "[INFO V6] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" -Color "Green" + if($currentStart -gt $script:EndDate){ + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) is greather than $($script:EndDate.ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) - are you sure you put in the correct year? Exiting!" -Color "Red" + return } - else { - $currentCount = $results.Count - if ($currentDay -ne 0){ - $currentTotal = $currentCount + $results.Count + + while ($currentStart -lt $script:EndDate) { + $currentEnd = $currentStart.AddMinutes($Interval) + Start-Sleep -Seconds 5 + if ($UserIds){ + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } } else { - $currentTotal = $currentCount + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." + try{ + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } + catch{ + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Start-Sleep -Seconds 30 + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + } } - - Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss HH:mm:ss"))" -Color "Green" + if ($null -eq $results -or $results.Count -eq 0) { + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")). Moving On!" -Color "Yellow" + } + else { + $currentCount = $results.Count + if ($currentDay -ne 0){ + $currentTotal = $currentCount + $results.Count + } + else { + $currentTotal = $currentCount + } - $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - - Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." - } - [Array]$results = @() - $CurrentStart = $CurrentEnd - $currentDay++ - } + Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" -Color "Green" + + $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" + $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - if ($MergeOutput.IsPresent) - { - Write-LogFile -Message "[INFO] Merging output files into one file" - $outputDirMerged = "$OutputDir\Merged\" - If (!(test-path $outputDirMerged)) { - Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" - New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null - } - - $allJsonObjects = @() - - Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { - $content = Get-Content -Path $_.FullName -Raw - $jsonObjects = $content | ConvertFrom-Json - $allJsonObjects += $jsonObjects + Write-LogFile -Message "[INFO] Successfully retrieved $($currentCount) records out of total $($currentTotal) for the current time range." + } + [Array]$results = @() + $CurrentStart = $CurrentEnd + $currentDay++ } + + if ($MergeOutput.IsPresent) + { + Write-LogFile -Message "[INFO] Merging output files into one file" + $outputDirMerged = "$OutputDir\Merged\" + If (!(test-path $outputDirMerged)) { + Write-LogFile -Message "[INFO] Creating the following directory: $outputDirMerged" + New-Item -ItemType Directory -Force -Path $outputDirMerged | Out-Null + } - $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\AuditLogs-Combined.json" - } + $allJsonObjects = @() - Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" -} - else { - $results = Get-AzureADAuditDirectoryLogs -All $true -Filter $filter - $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding - } - Write-logFile -Message "[INFO] Directory audit logs written to $filePath" -Color "Green" -} + Get-ChildItem $OutputDir -Filter *.json | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $jsonObjects = $content | ConvertFrom-Json + $allJsonObjects += $jsonObjects + } + + $allJsonObjects | ConvertTo-Json -Depth 100 | Set-Content "$outputDirMerged\AuditLogs-Combined.json" + } + + Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" + } \ No newline at end of file From 95a68af32fa4b243a922e5181b00ff3e6adb33e0 Mon Sep 17 00:00:00 2001 From: JoeyInvictus <129975292+JoeyInvictus@users.noreply.github.com> Date: Wed, 22 May 2024 09:06:05 +0200 Subject: [PATCH 7/7] Update Get-AzureADLogs.ps1 --- Scripts/Get-AzureADLogs.ps1 | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Scripts/Get-AzureADLogs.ps1 b/Scripts/Get-AzureADLogs.ps1 index 5f018f7..06841ba 100644 --- a/Scripts/Get-AzureADLogs.ps1 +++ b/Scripts/Get-AzureADLogs.ps1 @@ -287,9 +287,9 @@ function Get-ADSignInLogs { [DateTime]$lastLog = $script:EndDate $currentDay = 0 - Write-LogFile -Message "[INFO V6] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" -Color "Green" + Write-LogFile -Message "[INFO] Extracting all available Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" if($currentStart -gt $script:EndDate){ - Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) is greather than $($script:EndDate.ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) - are you sure you put in the correct year? Exiting!" -Color "Red" + Write-LogFile -Message "[ERROR] $($currentStart.ToString("yyyy-MM-ddTHH:mm:ssZ")) is greather than $($script:EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ")) - are you sure you put in the correct year? Exiting!" -Color "Red" return } @@ -297,31 +297,31 @@ function Get-ADSignInLogs { $currentEnd = $currentStart.AddMinutes($Interval) Start-Sleep -Seconds 5 if ($UserIds){ - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "initiatedBy/user/userPrincipalName eq '$Userids' and activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } } else { - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." try{ - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } catch{ - Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" + Write-LogFile -Message "[WARNING] Failed to acquire logs $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Retrying after sleep " -Color "Yellow" Start-Sleep -Seconds 30 - Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))." - [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails + Write-LogFile -Message "[INFO] Collecting Directory Audit logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))." + [Array]$results = Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime gt $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and activityDateTime lt $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" | Select-Object Id,Category,CorrelationId,Result,ResultReason,ActivityDisplayName,@{N='ActivityDateTime';E={$_.ActivityDateTime.ToString()}},LoggedByService,OperationType,InitiatedBy,TargetResources,AdditionalDetails } } if ($null -eq $results -or $results.Count -eq 0) { - Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")). Moving On!" -Color "Yellow" + Write-LogFile -Message "[WARNING] Empty data set returned between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")). Moving On!" -Color "Yellow" } else { $currentCount = $results.Count @@ -332,7 +332,7 @@ function Get-ADSignInLogs { $currentTotal = $currentCount } - Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZTHH:mm:ssZ"))" -Color "Green" + Write-LogFile -Message "[INFO] Found $currentCount Directory Audit Logs between $($currentStart.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")) and $($currentEnd.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"))" -Color "Green" $filePath = "$OutputDir\AuditLogs-$($CurrentStart.ToString("yyyyMMddHHmmss"))-$($CurrentEnd.ToString("yyyyMMddHHmmss")).json" $results | ConvertTo-Json -Depth 100 | Out-File -Append $filePath -Encoding $Encoding @@ -365,4 +365,4 @@ function Get-ADSignInLogs { } Write-LogFile -Message "[INFO] Acquisition complete, check the $($OutputDir) directory for your files.." -Color "Green" - } \ No newline at end of file + }