M365FoundationsCISReport.psm1

#Region '.\Classes\CISAuditResult.ps1' -1

class CISAuditResult {
    [string]$Status
    [string]$ELevel
    [string]$ProfileLevel
    [bool]$Automated
    [string]$Connection
    [string]$Rec
    [string]$RecDescription
    [string]$CISControlVer = 'v8'
    [string]$CISControl
    [string]$CISDescription
    [bool]$IG1
    [bool]$IG2
    [bool]$IG3
    [bool]$Result
    [string]$Details
    [string]$FailureReason
}
#EndRegion '.\Classes\CISAuditResult.ps1' 19
#Region '.\Private\Assert-ModuleAvailability.ps1' -1

function Assert-ModuleAvailability {
    param(
        [string]$ModuleName,
        [string]$RequiredVersion,
        [string]$SubModuleName
    )

    try {
        $module = Get-Module -ListAvailable -Name $ModuleName | Where-Object { $_.Version -ge [version]$RequiredVersion }

        if ($null -eq $module) {$auditResult.Profile
            Write-Host "Installing $ModuleName module..."
            Install-Module -Name $ModuleName -RequiredVersion $RequiredVersion -Force -AllowClobber -Scope CurrentUser | Out-Null
        }
        elseif ($module.Version -lt [version]$RequiredVersion) {
            Write-Host "Updating $ModuleName module to required version..."
            Update-Module -Name $ModuleName -RequiredVersion $RequiredVersion -Force | Out-Null
        }
        else {
            Write-Host "$ModuleName module is already at required version or newer."
        }

        if ($SubModuleName) {
            Import-Module -Name "$ModuleName.$SubModuleName" -RequiredVersion $RequiredVersion -ErrorAction Stop | Out-Null
        }
        else {
            Import-Module -Name $ModuleName -RequiredVersion $RequiredVersion -ErrorAction Stop | Out-Null
        }
    }
    catch {
        Write-Warning "An error occurred with module $ModuleName`: $_"
    }
}
#EndRegion '.\Private\Assert-ModuleAvailability.ps1' 34
#Region '.\Private\Connect-M365Suite.ps1' -1

function Connect-M365Suite {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false)]
        [string]$TenantAdminUrl,

        [Parameter(Mandatory)]
        [string[]]$RequiredConnections
    )

    $VerbosePreference = "SilentlyContinue"

    try {
        if ($RequiredConnections -contains "AzureAD" -or $RequiredConnections -contains "AzureAD | EXO" -or $RequiredConnections -contains "AzureAD | EXO | Microsoft Graph") {
            Write-Host "Connecting to Azure Active Directory..." -ForegroundColor Cyan
            Connect-AzureAD | Out-Null
            Write-Host "Successfully connected to Azure Active Directory." -ForegroundColor Green
        }

        if ($RequiredConnections -contains "Microsoft Graph" -or $RequiredConnections -contains "AzureAD | EXO | Microsoft Graph") {
            Write-Host "Connecting to Microsoft Graph with scopes: Directory.Read.All, Domain.Read.All, Policy.Read.All, Organization.Read.All" -ForegroundColor Cyan
            try {
                Connect-MgGraph -Scopes "Directory.Read.All", "Domain.Read.All", "Policy.Read.All", "Organization.Read.All" -NoWelcome | Out-Null
                Write-Host "Successfully connected to Microsoft Graph with specified scopes." -ForegroundColor Green
            }
            catch {
                Write-Host "Failed to connect to MgGraph, attempting device auth." -ForegroundColor Yellow
                Connect-MgGraph -Scopes "Directory.Read.All", "Domain.Read.All", "Policy.Read.All", "Organization.Read.All" -UseDeviceCode -NoWelcome | Out-Null
                Write-Host "Successfully connected to Microsoft Graph with specified scopes." -ForegroundColor Green
            }
        }

        if ($RequiredConnections -contains "EXO" -or $RequiredConnections -contains "AzureAD | EXO" -or $RequiredConnections -contains "Microsoft Teams | EXO" -or $RequiredConnections -contains "AzureAD | EXO | Microsoft Graph") {
            Write-Host "Connecting to Exchange Online..." -ForegroundColor Cyan
            Connect-ExchangeOnline | Out-Null
            Write-Host "Successfully connected to Exchange Online." -ForegroundColor Green
        }

        if ($RequiredConnections -contains "SPO") {
            Write-Host "Connecting to SharePoint Online..." -ForegroundColor Cyan
            Connect-SPOService -Url $TenantAdminUrl | Out-Null
            Write-Host "Successfully connected to SharePoint Online." -ForegroundColor Green
        }

        if ($RequiredConnections -contains "Microsoft Teams" -or $RequiredConnections -contains "Microsoft Teams | EXO") {
            Write-Host "Connecting to Microsoft Teams..." -ForegroundColor Cyan
            Connect-MicrosoftTeams | Out-Null
            Write-Host "Successfully connected to Microsoft Teams." -ForegroundColor Green
        }
    }
    catch {
        $VerbosePreference = "Continue"
        Write-Host "There was an error establishing one or more connections: $_" -ForegroundColor Red
        throw $_
    }

    $VerbosePreference = "Continue"
}
#EndRegion '.\Private\Connect-M365Suite.ps1' 59
#Region '.\Private\Disconnect-M365Suite.ps1' -1

function Disconnect-M365Suite {
    param (
        [Parameter(Mandatory)]
        [string[]]$RequiredConnections
    )

    # Clean up sessions
    try {
        if ($RequiredConnections -contains "EXO" -or $RequiredConnections -contains "AzureAD | EXO" -or $RequiredConnections -contains "Microsoft Teams | EXO") {
            Write-Host "Disconnecting from Exchange Online..." -ForegroundColor Green
            Disconnect-ExchangeOnline -Confirm:$false | Out-Null
        }
    }
    catch {
        Write-Warning "Failed to disconnect from Exchange Online: $_"
    }

    try {
        if ($RequiredConnections -contains "AzureAD" -or $RequiredConnections -contains "AzureAD | EXO") {
            Write-Host "Disconnecting from Azure AD..." -ForegroundColor Green
            Disconnect-AzureAD | Out-Null
        }
    }
    catch {
        Write-Warning "Failed to disconnect from Azure AD: $_"
    }

    try {
        if ($RequiredConnections -contains "Microsoft Graph") {
            Write-Host "Disconnecting from Microsoft Graph..." -ForegroundColor Green
            Disconnect-MgGraph | Out-Null
        }
    }
    catch {
        Write-Warning "Failed to disconnect from Microsoft Graph: $_"
    }

    try {
        if ($RequiredConnections -contains "SPO") {
            Write-Host "Disconnecting from SharePoint Online..." -ForegroundColor Green
            Disconnect-SPOService | Out-Null
        }
    }
    catch {
        Write-Warning "Failed to disconnect from SharePoint Online: $_"
    }

    try {
        if ($RequiredConnections -contains "Microsoft Teams" -or $RequiredConnections -contains "Microsoft Teams | EXO") {
            Write-Host "Disconnecting from Microsoft Teams..." -ForegroundColor Green
            Disconnect-MicrosoftTeams | Out-Null
        }
    }
    catch {
        Write-Warning "Failed to disconnect from Microsoft Teams: $_"
    }

    Write-Host "All necessary sessions have been disconnected." -ForegroundColor Green
}
#EndRegion '.\Private\Disconnect-M365Suite.ps1' 60
#Region '.\Private\Format-MissingAction.ps1' -1

function Format-MissingAction {
    param ([array]$missingActions)

    $actionGroups = @{
        "Admin"    = @()
        "Delegate" = @()
        "Owner"    = @()
    }

    foreach ($action in $missingActions) {
        if ($action -match "(Admin|Delegate|Owner) action '([^']+)' missing") {
            $type = $matches[1]
            $actionName = $matches[2]
            $actionGroups[$type] += $actionName
        }
    }

    $formattedResults = @{
        Admin    = $actionGroups["Admin"] -join ', '
        Delegate = $actionGroups["Delegate"] -join ', '
        Owner    = $actionGroups["Owner"] -join ', '
    }

    return $formattedResults
}
#EndRegion '.\Private\Format-MissingAction.ps1' 26
#Region '.\Private\Get-MostCommonWord.ps1' -1

function Get-MostCommonWord {
    param (
        [Parameter(Mandatory = $true)]
        [string[]]$InputStrings
    )

    # Combine all strings into one large string
    $allText = $InputStrings -join ' '

    # Split the large string into words
    $words = $allText -split '\s+'

    # Group words and count occurrences
    $wordGroups = $words | Group-Object | Sort-Object Count -Descending

    # Return the most common word if it occurs at least 3 times
    if ($wordGroups.Count -gt 0 -and $wordGroups[0].Count -ge 3) {
        return $wordGroups[0].Name
    } else {
        return $null
    }
}
#EndRegion '.\Private\Get-MostCommonWord.ps1' 23
#Region '.\Private\Get-RequiredModule.ps1' -1

function Get-RequiredModule {
    [CmdletBinding(DefaultParameterSetName = 'AuditFunction')]
    [OutputType([System.Object[]])]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = 'AuditFunction')]
        [switch]$AuditFunction,

        [Parameter(Mandatory = $true, ParameterSetName = 'SyncFunction')]
        [switch]$SyncFunction
    )

    switch ($PSCmdlet.ParameterSetName) {
        'AuditFunction' {
            return @(
                @{ ModuleName = "ExchangeOnlineManagement"; RequiredVersion = "3.3.0" },
                @{ ModuleName = "AzureAD"; RequiredVersion = "2.0.2.182" },
                @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModuleName = "Authentication" },
                @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModuleName = "Users" },
                @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModuleName = "Groups" },
                @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModuleName = "DirectoryObjects" },
                @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModuleName = "Domains" },
                @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModuleName = "Reports" },
                @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModuleName = "Mail" },
                @{ ModuleName = "Microsoft.Online.SharePoint.PowerShell"; RequiredVersion = "16.0.24009.12000" },
                @{ ModuleName = "MicrosoftTeams"; RequiredVersion = "5.5.0" }
            )
        }
        'SyncFunction' {
            return @(
                @{ ModuleName = "ImportExcel"; RequiredVersion = "7.8.9" }
            )
        }
        default {
            throw "Please specify either -AuditFunction or -SyncFunction switch."
        }
    }
}
#EndRegion '.\Private\Get-RequiredModule.ps1' 38
#Region '.\Private\Get-TestDefinitionsObject.ps1' -1

function Get-TestDefinitionsObject {
    param (
        [Parameter(Mandatory = $true)]
        [object[]]$TestDefinitions,

        [Parameter(Mandatory = $true)]
        [string]$ParameterSetName,

        [string]$ELevel,
        [string]$ProfileLevel,
        [string[]]$IncludeRecommendation,
        [string[]]$SkipRecommendation
    )

    Write-Verbose "Initial test definitions count: $($TestDefinitions.Count)"

    switch ($ParameterSetName) {
        'ELevelFilter' {
            Write-Verbose "Applying ELevelFilter"
            if ($null -ne $ELevel -and $null -ne $ProfileLevel) {
                Write-Verbose "Filtering on ELevel = $ELevel and ProfileLevel = $ProfileLevel"
                $TestDefinitions = $TestDefinitions | Where-Object {
                    $_.ELevel -eq $ELevel -and $_.ProfileLevel -eq $ProfileLevel
                }
            }
            elseif ($null -ne $ELevel) {
                Write-Verbose "Filtering on ELevel = $ELevel"
                $TestDefinitions = $TestDefinitions | Where-Object {
                    $_.ELevel -eq $ELevel
                }
            }
            elseif ($null -ne $ProfileLevel) {
                Write-Verbose "Filtering on ProfileLevel = $ProfileLevel"
                $TestDefinitions = $TestDefinitions | Where-Object {
                    $_.ProfileLevel -eq $ProfileLevel
                }
            }
        }
        'IG1Filter' {
            Write-Verbose "Applying IG1Filter"
            $TestDefinitions = $TestDefinitions | Where-Object { $_.IG1 -eq 'TRUE' }
        }
        'IG2Filter' {
            Write-Verbose "Applying IG2Filter"
            $TestDefinitions = $TestDefinitions | Where-Object { $_.IG2 -eq 'TRUE' }
        }
        'IG3Filter' {
            Write-Verbose "Applying IG3Filter"
            $TestDefinitions = $TestDefinitions | Where-Object { $_.IG3 -eq 'TRUE' }
        }
        'RecFilter' {
            Write-Verbose "Applying RecFilter"
            $TestDefinitions = $TestDefinitions | Where-Object { $IncludeRecommendation -contains $_.Rec }
        }
        'SkipRecFilter' {
            Write-Verbose "Applying SkipRecFilter"
            $TestDefinitions = $TestDefinitions | Where-Object { $SkipRecommendation -notcontains $_.Rec }
        }
    }

    Write-Verbose "Filtered test definitions count: $($TestDefinitions.Count)"
    return $TestDefinitions
}
#EndRegion '.\Private\Get-TestDefinitionsObject.ps1' 64
#Region '.\Private\Initialize-CISAuditResult.ps1' -1

function Initialize-CISAuditResult {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Rec,

        [Parameter(Mandatory = $true, ParameterSetName = 'Full')]
        [bool]$Result,

        [Parameter(Mandatory = $true, ParameterSetName = 'Full')]
        [string]$Status,

        [Parameter(Mandatory = $true, ParameterSetName = 'Full')]
        [string]$Details,

        [Parameter(Mandatory = $true, ParameterSetName = 'Full')]
        [string]$FailureReason,

        [Parameter(ParameterSetName = 'Error')]
        [switch]$Failure
    )

    # Import the test definitions CSV file
    $testDefinitions = $script:TestDefinitionsObject

    # Find the row that matches the provided recommendation (Rec)
    $testDefinition = $testDefinitions | Where-Object { $_.Rec -eq $Rec }

    if (-not $testDefinition) {
        throw "Test definition for recommendation '$Rec' not found."
    }

    # Create an instance of CISAuditResult and populate it
    $auditResult = [CISAuditResult]::new()
    $auditResult.Rec = $Rec
    $auditResult.ELevel = $testDefinition.ELevel
    $auditResult.ProfileLevel = $testDefinition.ProfileLevel
    $auditResult.IG1 = [bool]::Parse($testDefinition.IG1)
    $auditResult.IG2 = [bool]::Parse($testDefinition.IG2)
    $auditResult.IG3 = [bool]::Parse($testDefinition.IG3)
    $auditResult.RecDescription = $testDefinition.RecDescription
    $auditResult.CISControl = $testDefinition.CISControl
    $auditResult.CISDescription = $testDefinition.CISDescription
    $auditResult.Automated = [bool]::Parse($testDefinition.Automated)
    $auditResult.Connection = $testDefinition.Connection
    $auditResult.CISControlVer = 'v8'

    if ($PSCmdlet.ParameterSetName -eq 'Full') {
        $auditResult.Result = $Result
        $auditResult.Status = $Status
        $auditResult.Details = $Details
        $auditResult.FailureReason = $FailureReason
    } elseif ($PSCmdlet.ParameterSetName -eq 'Error') {
        $auditResult.Result = $false
        $auditResult.Status = 'Fail'
        $auditResult.Details = "An error occurred while processing the test."
        $auditResult.FailureReason = "Initialization error: Failed to process the test."
    }

    return $auditResult
}
#EndRegion '.\Private\Initialize-CISAuditResult.ps1' 62
#Region '.\Private\Invoke-TestFunction.ps1' -1

function Invoke-TestFunction {
    param (
        [Parameter(Mandatory = $true)]
        [PSObject]$FunctionFile,

        [Parameter(Mandatory = $false)]
        [string]$DomainName
    )

    $functionName = $FunctionFile.BaseName
    $functionCmd = Get-Command -Name $functionName

    # Check if the test function needs DomainName parameter
    $paramList = @{}
    if ('DomainName' -in $functionCmd.Parameters.Keys) {
        $paramList.DomainName = $DomainName
    }

    # Use splatting to pass parameters
    Write-Verbose "Running $functionName..."
    try {
        $result = & $functionName @paramList
        # Assuming each function returns an array of CISAuditResult or a single CISAuditResult
        return $result
    }
    catch {
        Write-Error "An error occurred during the test: $_"
        $script:FailedTests.Add([PSCustomObject]@{ Test = $functionName; Error = $_ })

        # Call Initialize-CISAuditResult with error parameters
        $auditResult = Initialize-CISAuditResult -Rec $functionName -Failure
        return $auditResult
    }
}
#EndRegion '.\Private\Invoke-TestFunction.ps1' 35
#Region '.\Private\Measure-AuditResult.ps1' -1

function Measure-AuditResult {
    param (
        [Parameter(Mandatory = $true)]
        [System.Collections.ArrayList]$AllAuditResults,

        [Parameter(Mandatory = $false)]
        [System.Collections.ArrayList]$FailedTests
    )

    # Calculate the total number of tests
    $totalTests = $AllAuditResults.Count

    # Calculate the number of passed tests
    $passedTests = $AllAuditResults.ToArray() | Where-Object { $_.Result -eq $true } | Measure-Object | Select-Object -ExpandProperty Count

    # Calculate the pass percentage
    $passPercentage = if ($totalTests -eq 0) { 0 } else { [math]::Round(($passedTests / $totalTests) * 100, 2) }

    # Display the pass percentage to the user
    Write-Host "Audit completed. $passedTests out of $totalTests tests passed." -ForegroundColor Cyan
    Write-Host "Your passing percentage is $passPercentage%."

    # Display details of failed tests
    if ($FailedTests.Count -gt 0) {
        Write-Host "The following tests failed to complete:" -ForegroundColor Red
        foreach ($failedTest in $FailedTests) {
            Write-Host "Test: $($failedTest.Test)" -ForegroundColor Yellow
            Write-Host "Error: $($failedTest.Error)" -ForegroundColor Yellow
        }
    }
}
#EndRegion '.\Private\Measure-AuditResult.ps1' 32
#Region '.\Private\Merge-CISExcelAndCsvData.ps1' -1

function Merge-CISExcelAndCsvData {
    [CmdletBinding(DefaultParameterSetName = 'CsvInput')]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ExcelPath,

        [Parameter(Mandatory = $true)]
        [string]$WorksheetName,

        [Parameter(Mandatory = $true, ParameterSetName = 'CsvInput')]
        [string]$CsvPath,

        [Parameter(Mandatory = $true, ParameterSetName = 'ObjectInput')]
        [CISAuditResult[]]$AuditResults
    )

    process {
        # Import data from Excel
        $import = Import-Excel -Path $ExcelPath -WorksheetName $WorksheetName

        # Import data from CSV or use provided object
        $csvData = if ($PSCmdlet.ParameterSetName -eq 'CsvInput') {
            Import-Csv -Path $CsvPath
        } else {
            $AuditResults
        }

        # Iterate over each item in the imported Excel object and merge with CSV data or audit results
        $mergedData = foreach ($item in $import) {
            $csvRow = $csvData | Where-Object { $_.Rec -eq $item.'recommendation #' }
            if ($csvRow) {
                New-MergedObject -ExcelItem $item -CsvRow $csvRow
            } else {
                New-MergedObject -ExcelItem $item -CsvRow ([PSCustomObject]@{Connection=$null;Status=$null; Details=$null; FailureReason=$null })
            }
        }

        # Return the merged data
        return $mergedData
    }
}
#EndRegion '.\Private\Merge-CISExcelAndCsvData.ps1' 42
#Region '.\Private\New-MergedObject.ps1' -1

function New-MergedObject {
    param (
        [Parameter(Mandatory = $true)]
        [psobject]$ExcelItem,

        [Parameter(Mandatory = $true)]
        [psobject]$CsvRow
    )

    $newObject = New-Object PSObject

    foreach ($property in $ExcelItem.PSObject.Properties) {
        $newObject | Add-Member -MemberType NoteProperty -Name $property.Name -Value $property.Value
    }
    $newObject | Add-Member -MemberType NoteProperty -Name 'CSV_Connection' -Value $CsvRow.Connection
    $newObject | Add-Member -MemberType NoteProperty -Name 'CSV_Status' -Value $CsvRow.Status
    $newObject | Add-Member -MemberType NoteProperty -Name 'CSV_Details' -Value $CsvRow.Details
    $newObject | Add-Member -MemberType NoteProperty -Name 'CSV_FailureReason' -Value $CsvRow.FailureReason
    return $newObject
}
#EndRegion '.\Private\New-MergedObject.ps1' 21
#Region '.\Private\Test-IsAdmin.ps1' -1

function Test-IsAdmin {
    <#
    .SYNOPSIS
    Checks if the current user is an administrator on the machine.
    .DESCRIPTION
    This private function returns a Boolean value indicating whether
    the current user has administrator privileges on the machine.
    It does this by creating a new WindowsPrincipal object, passing
    in a WindowsIdentity object representing the current user, and
    then checking if that principal is in the Administrator role.
    .INPUTS
    None.
    .OUTPUTS
    Boolean. Returns True if the current user is an administrator, and False otherwise.
    .EXAMPLE
    PS C:\> Test-IsAdmin
    True
    #>


    # Create a new WindowsPrincipal object for the current user and check if it is in the Administrator role
    (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
#EndRegion '.\Private\Test-IsAdmin.ps1' 23
#Region '.\Private\Update-CISExcelWorksheet.ps1' -1

function Update-CISExcelWorksheet {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ExcelPath,

        [Parameter(Mandatory = $true)]
        [string]$WorksheetName,

        [Parameter(Mandatory = $true)]
        [psobject[]]$Data,

        [Parameter(Mandatory = $false)]
        [int]$StartingRowIndex = 2 # Default starting row index, assuming row 1 has headers
    )

    process {
        # Load the existing Excel sheet
        $excelPackage = Open-ExcelPackage -Path $ExcelPath
        $worksheet = $excelPackage.Workbook.Worksheets[$WorksheetName]

        if (-not $worksheet) {
            throw "Worksheet '$WorksheetName' not found in '$ExcelPath'"
        }


        # Update the worksheet with the provided data
        Update-WorksheetCell -Worksheet $worksheet -Data $Data -StartingRowIndex $StartingRowIndex

        # Save and close the Excel package
        Close-ExcelPackage $excelPackage
    }
}
#EndRegion '.\Private\Update-CISExcelWorksheet.ps1' 34
#Region '.\Private\Update-WorksheetCell.ps1' -1

        function Update-WorksheetCell {
            param (
                $Worksheet,
                $Data,
                $StartingRowIndex
            )

            # Check and set headers
            $firstItem = $Data[0]
            $colIndex = 1
            foreach ($property in $firstItem.PSObject.Properties) {
                if ($StartingRowIndex -eq 2 -and $Worksheet.Cells[1, $colIndex].Value -eq $null) {
                    $Worksheet.Cells[1, $colIndex].Value = $property.Name
                }
                $colIndex++
            }

            # Iterate over each row in the data and update cells
            $rowIndex = $StartingRowIndex
            foreach ($item in $Data) {
                $colIndex = 1
                foreach ($property in $item.PSObject.Properties) {
                    $Worksheet.Cells[$rowIndex, $colIndex].Value = $property.Value
                    $colIndex++
                }
                $rowIndex++
            }
        }
#EndRegion '.\Private\Update-WorksheetCell.ps1' 29
#Region '.\Private\Write-AuditLog.ps1' -1

function Write-AuditLog {
    <#
    .SYNOPSIS
        Writes log messages to the console and updates the script-wide log variable.
    .DESCRIPTION
        The Write-AuditLog function writes log messages to the console based on the severity (Verbose, Warning, or Error) and updates
        the script-wide log variable ($script:LogString) with the log entry. You can use the Start, End, and EndFunction switches to
        manage the lifecycle of the logging.
    .INPUTS
        System.String
        You can pipe a string to the Write-AuditLog function as the Message parameter.
        You can also pipe an object with a Severity property as the Severity parameter.
    .OUTPUTS
        None
        The Write-AuditLog function doesn't output any objects to the pipeline. It writes messages to the console and updates the
        script-wide log variable ($script:LogString).
    .PARAMETER BeginFunction
        Sets the message to "Begin [FunctionName] function log.", where FunctionName is the name of the calling function, and adds it to the log variable.
    .PARAMETER Message
        The message string to log.
    .PARAMETER Severity
        The severity of the log message. Accepted values are 'Information', 'Warning', and 'Error'. Defaults to 'Information'.
    .PARAMETER Start
        Initializes the script-wide log variable and sets the message to "Begin [FunctionName] Log.", where FunctionName is the name of the calling function.
    .PARAMETER End
        Sets the message to "End Log" and exports the log to a CSV file if the OutputPath parameter is provided.
    .PARAMETER EndFunction
        Sets the message to "End [FunctionName] log.", where FunctionName is the name of the calling function, and adds it to the log variable.
    .PARAMETER OutputPath
        The file path for exporting the log to a CSV file when using the End switch.
    .EXAMPLE
        Write-AuditLog -Message "This is a test message."
 
        Writes a test message with the default severity (Information) to the console and adds it to the log variable.
    .EXAMPLE
        Write-AuditLog -Message "This is a warning message." -Severity "Warning"
 
        Writes a warning message to the console and adds it to the log variable.
    .EXAMPLE
        Write-AuditLog -Start
 
        Initializes the log variable and sets the message to "Begin [FunctionName] Log.", where FunctionName is the name of the calling function.
    .EXAMPLE
        Write-AuditLog -BeginFunction
 
        Sets the message to "Begin [FunctionName] function log.", where FunctionName is the name of the calling function, and adds it to the log variable.
    .EXAMPLE
        Write-AuditLog -EndFunction
 
        Sets the message to "End [FunctionName] log.", where FunctionName is the name of the calling function, and adds it to the log variable.
    .EXAMPLE
        Write-AuditLog -End -OutputPath "C:\Logs\auditlog.csv"
 
        Sets the message to "End Log", adds it to the log variable, and exports the log to a CSV file.
    .NOTES
    Author: DrIOSx
#>

    [CmdletBinding(DefaultParameterSetName = 'Default')]
    param(
        ###
        [Parameter(
            Mandatory = $false,
            HelpMessage = 'Input a Message string.',
            Position = 0,
            ParameterSetName = 'Default',
            ValueFromPipeline = $true
        )]
        [ValidateNotNullOrEmpty()]
        [string]$Message,
        ###
        [Parameter(
            Mandatory = $false,
            HelpMessage = 'Information, Warning or Error.',
            Position = 1,
            ParameterSetName = 'Default',
            ValueFromPipelineByPropertyName = $true
        )]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('Information', 'Warning', 'Error')]
        [string]$Severity = 'Information',
        ###
        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'End'
        )]
        [switch]$End,
        ###
        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'BeginFunction'
        )]
        [switch]$BeginFunction,
        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'EndFunction'
        )]
        [switch]$EndFunction,
        ###
        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'Start'
        )]
        [switch]$Start,
        ###
        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'End'
        )]
        [string]$OutputPath
    )
    begin {
        $ErrorActionPreference = "SilentlyContinue"
        # Define variables to hold information about the command that was invoked.
        $ModuleName = $Script:MyInvocation.MyCommand.Name -replace '\..*'
        $callStack = Get-PSCallStack
        if ($callStack.Count -gt 1) {
            $FuncName = $callStack[1].Command
        } else {
            $FuncName = "DirectCall"  # Or any other default name you prefer
        }
        #Write-Verbose "Funcname Name is $FuncName!" -Verbose
        $ModuleVer = $MyInvocation.MyCommand.Version.ToString()
        # Set the error action preference to continue.
        $ErrorActionPreference = "Continue"
    }
    process {
        try {
            if (-not $Start -and -not (Test-Path variable:script:LogString)) {
                throw "The logging variable is not initialized. Please call Write-AuditLog with the -Start switch or ensure $script:LogString is set."
            }
            $Function = $($FuncName + '.v' + $ModuleVer)
            if ($Start) {
                $script:LogString = @()
                $Message = '+++ Begin Log | ' + $Function + ' |'
            }
            elseif ($BeginFunction) {
                $Message = '>>> Begin Function Log | ' + $Function + ' |'
            }
            $logEntry = [pscustomobject]@{
                Time      = ((Get-Date).ToString('yyyy-MM-dd hh:mmTss'))
                Module    = $ModuleName
                PSVersion = ($PSVersionTable.PSVersion).ToString()
                PSEdition = ($PSVersionTable.PSEdition).ToString()
                IsAdmin   = $(Test-IsAdmin)
                User      = "$Env:USERDOMAIN\$Env:USERNAME"
                HostName  = $Env:COMPUTERNAME
                InvokedBy = $Function
                Severity  = $Severity
                Message   = $Message
                RunID     = -1
            }
            if ($BeginFunction) {
                $maxRunID = ($script:LogString | Where-Object { $_.InvokedBy -eq $Function } | Measure-Object -Property RunID -Maximum).Maximum
                if ($null -eq $maxRunID) { $maxRunID = -1 }
                $logEntry.RunID = $maxRunID + 1
            }
            else {
                $lastRunID = ($script:LogString | Where-Object { $_.InvokedBy -eq $Function } | Select-Object -Last 1).RunID
                if ($null -eq $lastRunID) { $lastRunID = 0 }
                $logEntry.RunID = $lastRunID
            }
            if ($EndFunction) {
                $FunctionStart = "$((($script:LogString | Where-Object {$_.InvokedBy -eq $Function -and $_.RunId -eq $lastRunID } | Sort-Object Time)[0]).Time)"
                $startTime = ([DateTime]::ParseExact("$FunctionStart", 'yyyy-MM-dd hh:mmTss', $null))
                $endTime = Get-Date
                $timeTaken = $endTime - $startTime
                $Message = '<<< End Function Log | ' + $Function + ' | Runtime: ' + "$($timeTaken.Minutes) min $($timeTaken.Seconds) sec"
                $logEntry.Message = $Message
            }
            elseif ($End) {
                $startTime = ([DateTime]::ParseExact($($script:LogString[0].Time), 'yyyy-MM-dd hh:mmTss', $null))
                $endTime = Get-Date
                $timeTaken = $endTime - $startTime
                $Message = '--- End Log | ' + $Function + ' | Runtime: ' + "$($timeTaken.Minutes) min $($timeTaken.Seconds) sec"
                $logEntry.Message = $Message
            }
            $script:LogString += $logEntry
            switch ($Severity) {
                'Warning' {
                    Write-Warning ('[WARNING] ! ' + $Message)
                    $UserInput = Read-Host "Warning encountered! Do you want to continue? (Y/N)"
                    if ($UserInput -eq 'N') {
                        throw "Script execution stopped by user."
                    }
                }
                'Error'       { Write-Error ('[ERROR] X - ' + $FuncName + ' ' + $Message) -ErrorAction Continue }
                'Verbose'     { Write-Verbose ('[VERBOSE] ~ ' + $Message) }
                Default { Write-Information ('[INFO] * ' + $Message)  -InformationAction Continue}
            }
        }
        catch {
            throw "Write-AuditLog encountered an error (process block): $($_)"
        }

    }
    end {
        try {
            if ($End) {
                if (-not [string]::IsNullOrEmpty($OutputPath)) {
                    $script:LogString | Export-Csv -Path $OutputPath -NoTypeInformation
                    Write-Verbose "LogPath: $(Split-Path -Path $OutputPath -Parent)"
                }
                else {
                    throw "OutputPath is not specified for End action."
                }
            }
        }
        catch {
            throw "Error in Write-AuditLog (end block): $($_.Exception.Message)"
        }
    }
}
#EndRegion '.\Private\Write-AuditLog.ps1' 213
#Region '.\Public\Get-AdminRoleUserLicense.ps1' -1

<#
.SYNOPSIS
    Retrieves user licenses and roles for administrative accounts from Microsoft 365 via the Graph API.
.DESCRIPTION
    The Get-AdminRoleUserLicense function connects to Microsoft Graph and retrieves all users who are assigned administrative roles along with their user details and licenses. This function is useful for auditing and compliance checks to ensure that administrators have appropriate licenses and role assignments.
.PARAMETER SkipGraphConnection
    A switch parameter that, when set, skips the connection to Microsoft Graph if already established. This is useful for batch processing or when used within scripts where multiple calls are made and the connection is managed externally.
.EXAMPLE
    PS> Get-AdminRoleUserLicense
 
    This example retrieves all administrative role users along with their licenses by connecting to Microsoft Graph using the default scopes.
.EXAMPLE
    PS> Get-AdminRoleUserLicense -SkipGraphConnection
 
    This example retrieves all administrative role users along with their licenses without attempting to connect to Microsoft Graph, assuming that the connection is already established.
.INPUTS
    None. You cannot pipe objects to Get-AdminRoleUserLicense.
.OUTPUTS
    PSCustomObject
    Returns a custom object for each user with administrative roles that includes the following properties: RoleName, UserName, UserPrincipalName, UserId, HybridUser, and Licenses.
.NOTES
    Creation Date: 2024-04-15
    Purpose/Change: Initial function development to support Microsoft 365 administrative role auditing.
.LINK
    https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Get-AdminRoleUserLicense
#>

function Get-AdminRoleUserLicense {
    # Set output type to System.Collections.ArrayList
    [OutputType([System.Collections.ArrayList])]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$SkipGraphConnection
    )

    begin {
        if (-not $SkipGraphConnection) {
            Connect-MgGraph -Scopes "Directory.Read.All", "Domain.Read.All", "Policy.Read.All", "Organization.Read.All" -NoWelcome
        }

        $adminRoleUsers = [System.Collections.ArrayList]::new()
        $userIds = [System.Collections.ArrayList]::new()
    }

    Process {
        $adminroles = Get-MgRoleManagementDirectoryRoleDefinition | Where-Object { $_.DisplayName -like "*Admin*" }

        foreach ($role in $adminroles) {
            $usersInRole = Get-MgRoleManagementDirectoryRoleAssignment -Filter "roleDefinitionId eq '$($role.Id)'"

            foreach ($user in $usersInRole) {
                $userDetails = Get-MgUser -UserId $user.PrincipalId -Property "DisplayName, UserPrincipalName, Id, onPremisesSyncEnabled" -ErrorAction SilentlyContinue

                if ($userDetails) {
                    [void]($userIds.Add($user.PrincipalId))
                    [void](
                        $adminRoleUsers.Add(
                            [PSCustomObject]@{
                                RoleName          = $role.DisplayName
                                UserName          = $userDetails.DisplayName
                                UserPrincipalName = $userDetails.UserPrincipalName
                                UserId            = $userDetails.Id
                                HybridUser        = $userDetails.onPremisesSyncEnabled
                                Licenses          = $null  # Initialize as $null
                            }
                        )
                    )
                }
            }
        }

        foreach ($userId in $userIds.ToArray() | Select-Object -Unique) {
            $licenses = Get-MgUserLicenseDetail -UserId $userId -ErrorAction SilentlyContinue
            if ($licenses) {
                $licenseList = ($licenses.SkuPartNumber -join '|')
                $adminRoleUsers.ToArray() | Where-Object { $_.UserId -eq $userId } | ForEach-Object {
                    $_.Licenses = $licenseList
                }
            }
        }
    }

    End {
        Write-Host "Disconnecting from Microsoft Graph..." -ForegroundColor Green
        Disconnect-MgGraph | Out-Null
        return $adminRoleUsers
    }
}
#EndRegion '.\Public\Get-AdminRoleUserLicense.ps1' 89
#Region '.\Public\Invoke-M365SecurityAudit.ps1' -1

<#
    .SYNOPSIS
    Invokes a security audit for Microsoft 365 environments.
    .DESCRIPTION
    The Invoke-M365SecurityAudit cmdlet performs a comprehensive security audit based on the specified parameters. It allows auditing of various configurations and settings within a Microsoft 365 environment, such as compliance with CIS benchmarks.
    .PARAMETER TenantAdminUrl
    The URL of the tenant admin. If not specified, none of the SharePoint Online tests will run.
    .PARAMETER M365DomainForPWPolicyTest
    The domain name of the Microsoft 365 environment to test. This parameter is not mandatory and by default it will pass/fail all found domains as a group if a specific domain is not specified.
    .PARAMETER ELevel
    Specifies the E-Level (E3 or E5) for the audit. This parameter is optional and can be combined with the ProfileLevel parameter.
    .PARAMETER ProfileLevel
    Specifies the profile level (L1 or L2) for the audit. This parameter is optional and can be combined with the ELevel parameter.
    .PARAMETER IncludeIG1
    If specified, includes tests where IG1 is true.
    .PARAMETER IncludeIG2
    If specified, includes tests where IG2 is true.
    .PARAMETER IncludeIG3
    If specified, includes tests where IG3 is true.
    .PARAMETER IncludeRecommendation
    Specifies specific recommendations to include in the audit. Accepts an array of recommendation numbers.
    .PARAMETER SkipRecommendation
    Specifies specific recommendations to exclude from the audit. Accepts an array of recommendation numbers.
    .PARAMETER DoNotConnect
    If specified, the cmdlet will not establish a connection to Microsoft 365 services.
    .PARAMETER DoNotDisconnect
    If specified, the cmdlet will not disconnect from Microsoft 365 services after execution.
    .PARAMETER NoModuleCheck
    If specified, the cmdlet will not check for the presence of required modules.
    .EXAMPLE
    PS> Invoke-M365SecurityAudit
    Performs a security audit using default parameters.
    Output:
    Status : Fail
    ELevel : E3
    ProfileLevel: L1
    Connection : Microsoft Graph
    Rec : 1.1.1
    Result : False
    Details : Non-compliant accounts:
                Username | Roles | HybridStatus | Missing Licence
                user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM
                user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2
    FailureReason: Non-Compliant Accounts: 2
    .EXAMPLE
    PS> Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com" -ELevel "E5" -ProfileLevel "L1"
    Performs a security audit for the E5 level and L1 profile in the specified Microsoft 365 environment.
    Output:
    Status : Fail
    ELevel : E5
    ProfileLevel: L1
    Connection : Microsoft Graph
    Rec : 1.1.1
    Result : False
    Details : Non-compliant accounts:
                Username | Roles | HybridStatus | Missing Licence
                user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM
                user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2
    FailureReason: Non-Compliant Accounts: 2
    .EXAMPLE
    PS> Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com" -IncludeIG1
    Performs an audit including all tests where IG1 is true.
    Output:
    Status : Fail
    ELevel : E3
    ProfileLevel: L1
    Connection : Microsoft Graph
    Rec : 1.1.1
    Result : False
    Details : Non-compliant accounts:
                Username | Roles | HybridStatus | Missing Licence
                user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM
                user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2
    FailureReason: Non-Compliant Accounts: 2
    .EXAMPLE
    PS> Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com" -SkipRecommendation '1.1.3', '2.1.1'
    Performs an audit while excluding specific recommendations 1.1.3 and 2.1.1.
    Output:
    Status : Fail
    ELevel : E3
    ProfileLevel: L1
    Connection : Microsoft Graph
    Rec : 1.1.1
    Result : False
    Details : Non-compliant accounts:
                Username | Roles | HybridStatus | Missing Licence
                user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM
                user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2
    FailureReason: Non-Compliant Accounts: 2
    .EXAMPLE
    PS> $auditResults = Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com"
    PS> $auditResults | Export-Csv -Path "auditResults.csv" -NoTypeInformation
    Captures the audit results into a variable and exports them to a CSV file.
    Output:
    CISAuditResult[]
    auditResults.csv
    .EXAMPLE
    PS> Invoke-M365SecurityAudit -WhatIf
    Displays what would happen if the cmdlet is run without actually performing the audit.
    Output:
    What if: Performing the operation "Invoke-M365SecurityAudit" on target "Microsoft 365 environment".
    .INPUTS
    None. You cannot pipe objects to Invoke-M365SecurityAudit.
    .OUTPUTS
    CISAuditResult[]
    The cmdlet returns an array of CISAuditResult objects representing the results of the security audit.
    .NOTES
    - This module is based on CIS benchmarks.
    - Governed by the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
    - Commercial use is not permitted. This module cannot be sold or used for commercial purposes.
    - Modifications and sharing are allowed under the same license.
    - For full license details, visit: https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en
    - Register for CIS Benchmarks at: https://www.cisecurity.org/cis-benchmarks
    .LINK
    https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Invoke-M365SecurityAudit
#>


function Invoke-M365SecurityAudit {
    [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'Default')]
    [OutputType([CISAuditResult[]])]
    param (
        [Parameter(Mandatory = $false, HelpMessage = "The SharePoint tenant admin URL, which should end with '-admin.sharepoint.com'. If not specified none of the Sharepoint Online tests will run.")]
        [ValidatePattern('^https://[a-zA-Z0-9-]+-admin\.sharepoint\.com$')]
        [string]$TenantAdminUrl,

        [Parameter(Mandatory = $false, HelpMessage = "Specify this to test only the default domain for password expiration policy when '1.3.1' is included in the tests to be run. The domain name of your organization, e.g., 'example.com'.")]
        [ValidatePattern('^[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$')]
        [string]$M365DomainForPWPolicyTest,

        # E-Level with optional ProfileLevel selection
        [Parameter(Mandatory = $true, ParameterSetName = 'ELevelFilter')]
        [ValidateSet('E3', 'E5')]
        [string]$ELevel,

        [Parameter(Mandatory = $true, ParameterSetName = 'ELevelFilter')]
        [ValidateSet('L1', 'L2')]
        [string]$ProfileLevel,

        # IG Filters, one at a time
        [Parameter(Mandatory = $true, ParameterSetName = 'IG1Filter')]
        [switch]$IncludeIG1,

        [Parameter(Mandatory = $true, ParameterSetName = 'IG2Filter')]
        [switch]$IncludeIG2,

        [Parameter(Mandatory = $true, ParameterSetName = 'IG3Filter')]
        [switch]$IncludeIG3,

        # Inclusion of specific recommendation numbers
        [Parameter(Mandatory = $true, ParameterSetName = 'RecFilter')]
        [ValidateSet(
            '1.1.1', '1.1.3', '1.2.1', '1.2.2', '1.3.1', '1.3.3', '1.3.6', '2.1.1', '2.1.2', `
            '2.1.3', '2.1.4', '2.1.5', '2.1.6', '2.1.7', '2.1.9', '3.1.1', '5.1.2.3', `
            '5.1.8.1', '6.1.1', '6.1.2', '6.1.3', '6.2.1', '6.2.2', '6.2.3', '6.3.1', `
            '6.5.1', '6.5.2', '6.5.3', '7.2.1', '7.2.10', '7.2.2', '7.2.3', '7.2.4', `
            '7.2.5', '7.2.6', '7.2.7', '7.2.9', '7.3.1', '7.3.2', '7.3.4', '8.1.1', `
            '8.1.2', '8.2.1', '8.5.1', '8.5.2', '8.5.3', '8.5.4', '8.5.5', '8.5.6', `
            '8.5.7', '8.6.1'
        )]
        [string[]]$IncludeRecommendation,

        # Exclusion of specific recommendation numbers
        [Parameter(Mandatory = $true, ParameterSetName = 'SkipRecFilter')]
        [ValidateSet(
            '1.1.1', '1.1.3', '1.2.1', '1.2.2', '1.3.1', '1.3.3', '1.3.6', '2.1.1', '2.1.2', `
            '2.1.3', '2.1.4', '2.1.5', '2.1.6', '2.1.7', '2.1.9', '3.1.1', '5.1.2.3', `
            '5.1.8.1', '6.1.1', '6.1.2', '6.1.3', '6.2.1', '6.2.2', '6.2.3', '6.3.1', `
            '6.5.1', '6.5.2', '6.5.3', '7.2.1', '7.2.10', '7.2.2', '7.2.3', '7.2.4', `
            '7.2.5', '7.2.6', '7.2.7', '7.2.9', '7.3.1', '7.3.2', '7.3.4', '8.1.1', `
            '8.1.2', '8.2.1', '8.5.1', '8.5.2', '8.5.3', '8.5.4', '8.5.5', '8.5.6', `
            '8.5.7', '8.6.1'
        )]
        [string[]]$SkipRecommendation,

        # Common parameters for all parameter sets
        [switch]$DoNotConnect,
        [switch]$DoNotDisconnect,
        [switch]$NoModuleCheck
    )

    Begin {
        if ($script:MaximumFunctionCount -lt 8192) {
            $script:MaximumFunctionCount = 8192
        }
        # Ensure required modules are installed
        if (!($NoModuleCheck) -and $PSCmdlet.ShouldProcess("Check for required modules", "Check")) {
            $requiredModules = Get-RequiredModule -AuditFunction
            foreach ($module in $requiredModules) {
                Assert-ModuleAvailability -ModuleName $module.ModuleName -RequiredVersion $module.RequiredVersion -SubModuleName $module.SubModuleName
            }
        }
        # Load test definitions from CSV
        $testDefinitionsPath = Join-Path -Path $PSScriptRoot -ChildPath "helper\TestDefinitions.csv"
        $testDefinitions = Import-Csv -Path $testDefinitionsPath
        # Load the Test Definitions into the script scope for use in other functions
        $script:TestDefinitionsObject = $testDefinitions

        # Apply filters based on parameter sets
        $params = @{
            TestDefinitions       = $testDefinitions
            ParameterSetName      = $PSCmdlet.ParameterSetName
            ELevel                = $ELevel
            ProfileLevel          = $ProfileLevel
            IncludeRecommendation = $IncludeRecommendation
            SkipRecommendation    = $SkipRecommendation
        }
        $testDefinitions = Get-TestDefinitionsObject @params
        # Extract unique connections needed
        $requiredConnections = $testDefinitions.Connection | Sort-Object -Unique
        if ($requiredConnections -contains 'SPO'){
            if (-not $TenantAdminUrl) {
                $requiredConnections = $requiredConnections | Where-Object { $_ -ne 'SPO' }
                $testDefinitions = $testDefinitions | Where-Object { $_.Connection -ne 'SPO' }
                if ($null -eq $testDefinitions) {
                    throw "No tests to run as no SharePoint Online tests are available."
                }
            }
        }
        # Determine which test files to load based on filtering
        $testsToLoad = $testDefinitions.TestFileName | ForEach-Object { $_ -replace '.ps1$', '' }
        Write-Verbose "The $(($testsToLoad).count) test/s that would be loaded based on filter criteria:"
        $testsToLoad | ForEach-Object { Write-Verbose " $_" }
        # Initialize a collection to hold failed test details
        $script:FailedTests = [System.Collections.ArrayList]::new()
    } # End Begin

    Process {
        $allAuditResults = [System.Collections.ArrayList]::new() # Initialize a collection to hold all results
        # Dynamically dot-source the test scripts
        $testsFolderPath = Join-Path -Path $PSScriptRoot -ChildPath "tests"
        $testFiles = Get-ChildItem -Path $testsFolderPath -Filter "Test-*.ps1" |
        Where-Object { $testsToLoad -contains $_.BaseName }

        $totalTests = $testFiles.Count
        $currentTestIndex = 0

        # Establishing connections if required
        if (!($DoNotConnect) -and $PSCmdlet.ShouldProcess("Establish connections to Microsoft 365 services", "Connect")) {
            Connect-M365Suite -TenantAdminUrl $TenantAdminUrl -RequiredConnections $requiredConnections
        }

        # Import the test functions
        $testFiles | ForEach-Object {
            $currentTestIndex++
            Write-Progress -Activity "Loading Test Scripts" -Status "Loading $($currentTestIndex) of $($totalTests): $($_.Name)" -PercentComplete (($currentTestIndex / $totalTests) * 100)
            Try {
                # Dot source the test function
                . $_.FullName
            }
            Catch {
                # Log the error and add the test to the failed tests collection
                Write-Error "Failed to load test function $($_.Name): $_"
                $script:FailedTests.Add([PSCustomObject]@{ Test = $_.Name; Error = $_ })
            }
        }

        $currentTestIndex = 0
        # Execute each test function from the prepared list
        foreach ($testFunction in $testFiles) {
            $currentTestIndex++
            Write-Progress -Activity "Executing Tests" -Status "Executing $($currentTestIndex) of $($totalTests): $($testFunction.Name)" -PercentComplete (($currentTestIndex / $totalTests) * 100)
            $functionName = $testFunction.BaseName
            if ($PSCmdlet.ShouldProcess($functionName, "Execute test")) {
                $auditResult = Invoke-TestFunction -FunctionFile $testFunction -DomainName $M365DomainForPWPolicyTest
                # Add the result to the collection
                [void]$allAuditResults.Add($auditResult)
            }
        }
    }

    End {
        if (!($DoNotDisconnect) -and $PSCmdlet.ShouldProcess("Disconnect from Microsoft 365 services", "Disconnect")) {
            # Clean up sessions
            Disconnect-M365Suite -RequiredConnections $requiredConnections
        }
        if ($PSCmdlet.ShouldProcess("Measure and display audit results", "Measure")) {
            # Call the private function to calculate and display results
            Measure-AuditResult -AllAuditResults $allAuditResults -FailedTests $script:FailedTests
            # Return all collected audit results
            return $allAuditResults.ToArray() | Sort-Object -Property Rec
        }
    }
}
#EndRegion '.\Public\Invoke-M365SecurityAudit.ps1' 284
#Region '.\Public\Sync-CISExcelAndCsvData.ps1' -1

<#
.SYNOPSIS
Synchronizes data between an Excel file and either a CSV file or an output object from Invoke-M365SecurityAudit, and optionally updates the Excel worksheet.
.DESCRIPTION
The Sync-CISExcelAndCsvData function merges data from a specified Excel file with data from either a CSV file or an output object from Invoke-M365SecurityAudit based on a common key. It can also update the Excel worksheet with the merged data. This function is particularly useful for updating Excel records with additional data from a CSV file or audit results while preserving the original formatting and structure of the Excel worksheet.
.PARAMETER ExcelPath
The path to the Excel file that contains the original data. This parameter is mandatory.
.PARAMETER WorksheetName
The name of the worksheet within the Excel file that contains the data to be synchronized. This parameter is mandatory.
.PARAMETER CsvPath
The path to the CSV file containing data to be merged with the Excel data. This parameter is mandatory when using the CsvInput parameter set.
.PARAMETER AuditResults
An array of CISAuditResult objects from Invoke-M365SecurityAudit to be merged with the Excel data. This parameter is mandatory when using the ObjectInput parameter set. It can also accept pipeline input.
.PARAMETER SkipUpdate
If specified, the function will return the merged data object without updating the Excel worksheet. This is useful for previewing the merged data.
.EXAMPLE
PS> Sync-CISExcelAndCsvData -ExcelPath "path\to\excel.xlsx" -WorksheetName "DataSheet" -CsvPath "path\to\data.csv"
Merges data from 'data.csv' into 'excel.xlsx' on the 'DataSheet' worksheet and updates the worksheet with the merged data.
.EXAMPLE
PS> $mergedData = Sync-CISExcelAndCsvData -ExcelPath "path\to\excel.xlsx" -WorksheetName "DataSheet" -CsvPath "path\to\data.csv" -SkipUpdate
Retrieves the merged data object for preview without updating the Excel worksheet.
.EXAMPLE
PS> $auditResults = Invoke-M365SecurityAudit -TenantAdminUrl "https://tenant-admin.url" -DomainName "example.com"
PS> Sync-CISExcelAndCsvData -ExcelPath "path\to\excel.xlsx" -WorksheetName "DataSheet" -AuditResults $auditResults
Merges data from the audit results into 'excel.xlsx' on the 'DataSheet' worksheet and updates the worksheet with the merged data.
.EXAMPLE
PS> $auditResults = Invoke-M365SecurityAudit -TenantAdminUrl "https://tenant-admin.url" -DomainName "example.com"
PS> $mergedData = Sync-CISExcelAndCsvData -ExcelPath "path\to\excel.xlsx" -WorksheetName "DataSheet" -AuditResults $auditResults -SkipUpdate
Retrieves the merged data object for preview without updating the Excel worksheet.
.EXAMPLE
PS> Invoke-M365SecurityAudit -TenantAdminUrl "https://tenant-admin.url" -DomainName "example.com" | Sync-CISExcelAndCsvData -ExcelPath "path\to\excel.xlsx" -WorksheetName "DataSheet"
Pipes the audit results into Sync-CISExcelAndCsvData to merge data into 'excel.xlsx' on the 'DataSheet' worksheet and updates the worksheet with the merged data.
.INPUTS
System.String, CISAuditResult[]
You can pipe CISAuditResult objects to Sync-CISExcelAndCsvData.
.OUTPUTS
Object[]
If the SkipUpdate switch is used, the function returns an array of custom objects representing the merged data.
.NOTES
- Ensure that the 'ImportExcel' module is installed and up to date.
- It is recommended to backup the Excel file before running this script to prevent accidental data loss.
- This function is part of the CIS Excel and CSV Data Management Toolkit.
.LINK
https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Sync-CISExcelAndCsvData
#>

function Sync-CISExcelAndCsvData {
    [CmdletBinding(DefaultParameterSetName = 'CsvInput')]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({ Test-Path $_ })]
        [string]$ExcelPath,

        [Parameter(Mandatory = $true)]
        [string]$WorksheetName,

        [Parameter(Mandatory = $true, ParameterSetName = 'CsvInput')]
        [ValidateScript({ Test-Path $_ })]
        [string]$CsvPath,

        [Parameter(Mandatory = $true, ParameterSetName = 'ObjectInput', ValueFromPipeline = $true)]
        [CISAuditResult[]]$AuditResults,

        [Parameter(Mandatory = $false)]
        [switch]$SkipUpdate
    )

    process {
        # Verify ImportExcel module is available
        $requiredModules = Get-RequiredModule -SyncFunction
        foreach ($module in $requiredModules) {
            Assert-ModuleAvailability -ModuleName $module.ModuleName -RequiredVersion $module.RequiredVersion -SubModuleName $module.SubModuleName
        }

        # Merge Excel and CSV data or Audit Results
        if ($PSCmdlet.ParameterSetName -eq 'CsvInput') {
            $mergedData = Merge-CISExcelAndCsvData -ExcelPath $ExcelPath -WorksheetName $WorksheetName -CsvPath $CsvPath
        } else {
            $mergedData = Merge-CISExcelAndCsvData -ExcelPath $ExcelPath -WorksheetName $WorksheetName -AuditResults $AuditResults
        }

        # Output the merged data if the user chooses to skip the update
        if ($SkipUpdate) {
            return $mergedData
        } else {
            # Update the Excel worksheet with the merged data
            Update-CISExcelWorksheet -ExcelPath $ExcelPath -WorksheetName $WorksheetName -Data $mergedData
        }
    }
}
#EndRegion '.\Public\Sync-CISExcelAndCsvData.ps1' 90