Public/Security/Get-RecentCFAEvents.ps1

function Get-RecentCFAEvents {
    <#
    .SYNOPSIS
    Retrieves recent block or audit events for Windows Controlled Folder Access.

    .DESCRIPTION
    This function queries the Windows Event Log for block (Event ID 1123) and audit (Event ID 1124) events related to Controlled Folder Access in the Microsoft-Windows-Windows Defender/Operational log. It includes error handling and suggests running as admin if access is denied.

    .PARAMETER DaysBack
    The number of days back to search for events. Default is 7 days.

    .EXAMPLE
    Get-RecentCFABlockEvents -DaysBack 1
    Retrieves events from the last 24 hours.

    .NOTES
    Based on Microsoft documentation, Event ID 1123 indicates blocked controlled folder access events, and 1124 for audited events.
    If you encounter access issues, run PowerShell as Administrator.
    #>


    param (
        [int]$DaysBack = 15
    )

    $Results = @()

    $startTime = (Get-Date).AddDays(-$DaysBack)

    try {
        $events = Get-WinEvent -FilterHashtable @{
            LogName   = 'Microsoft-Windows-Windows Defender/Operational'
            ID        = 1123, 1124
            StartTime = $startTime
        } -ErrorAction Stop

        if ($events) {
            $events | ForEach-Object {
                $Results += [PSCustomObject]@{
                    TimeCreated = $_.TimeCreated
                    EventID     = $_.Id
                    Message     = $_.Message
                }
            }
        } else {
            Write-Verbose "No recent block or audit events found for Controlled Folder Access in the last $DaysBack days."
        }
    } catch {
        Write-Verbose "Error accessing the event log: $($_.Exception.Message)"
        Write-Verbose "This may require running PowerShell as Administrator."
        Write-Verbose "You can also manually check in Event Viewer under Applications and Services Logs > Microsoft > Windows > Windows Defender > Operational."
    }

    RETURN $Results
}
New-Alias -Name Get-RecentControlledFolderAccessEvents -Value Get-RecentCFAEvents