Public/Get-ReportsAuditEvents.ps1

Function Get-ReportsAuditEvents {
    <#
        .SYNOPSIS
        Returns the selected Audit Events.
 
        .DESCRIPTION
        Despite the "GET" title, this is infact a "POST" method. It takes in options and sends them up.
 
        .PARAMETER Top
        Sets a limit for the maximum number of results returned.
 
        .PARAMETER Category
        Allows you to select the category for audit log review. Unsure if required at this time...
 
        .PARAMETER SortOption
        Allows you to select a sort function.
 
        .PARAMETER startDateTime
        Allows you to select a start date for searching
 
        .PARAMETER endDateTime
        Allows you to select an end date for searching
 
        .LINK
        https://github.com/nouselesstech/MsftIamApi
    #>

    param(
        [string]$category,
        [string]$sortOption,
        [string]$startDateTime,
        [string]$endDateTime,
        [int]$top
    )

    try {
        if ($Null -eq $Global:IamToken) {
            throw "Authenticate with Connect-MsftIamApi before running this command."
        }

        $Response = $Null

        ## Prepare Request
        $Headers = @{}
        $Headers.Authorization              = "Bearer $($Global:IamToken.access_token)"
        $Headers.'Content-Type'             = 'application/json'
        $Headers.'Accept'                   = '*/*'
        $Headers.'User-Agent'               = 'NoUselessTech.IamFetcher'
        $Headers.'X-Ms-Client-Request-Id'   = (New-Guid).Guid
        
        $Method = 'POST'

        $Body = @{}

        if ($category)      { $Body.category = $category }
        if ($sortOption)    { $Body.sortOption = $sortOption }
        if ($top)           { $Body.top = $top }
        if ($endDateTime)   { $Body.endDateTime = $endDateTime }
        if ($startDateTime) { $Body.startDateTime = $startDateTime }

        ## Send the Request
        $Response = (Invoke-WebRequest `
                        -Uri "https://main.iam.ad.ext.azure.com/api/Reports/AuditEventsV2" `
                        -Headers $Headers `
                        -Body ($Body | ConvertTo-Json) `
                        -Method $Method).Content | ConvertFrom-Json -Depth 100
        
        return $Response.items

    } catch {
        throw "Could not get Audit Events. $_"
    }
}