Start-IntuneRemediationTranscript.psm1

function Start-IntuneRemediationTranscript {
    [CmdletBinding()]
    param(
        [string]$LogName,
        [string]$LogDirectory = "$env:HomeDrive\ProgramData\Microsoft\IntuneManagementExtension\Logs",
        [string]$ErrorLogDirectory = "$env:ProgramData\ErrorLogs",
        [int]$SizeThresholdMB = 5,
        [switch]$Stop
    )
    # Handle stopping the transcript
    if ($Stop) {
        if ($global:TranscriptionStatus -eq $false) {
            Write-Warning "No active transcript found."
        } else {
            try {
                Stop-Transcript
                $global:TranscriptionStatus = $false
                Write-Output "Transcript stopped successfully."
            } catch {
                $ErrorMessage = "Failed to stop transcript: $_.Exception.Message"
                Write-Warning $ErrorMessage
                Log-ErrorToFile $ErrorMessage
            }
        }
        return
    }

    # Validate LogName
    if ([string]::IsNullOrWhiteSpace($LogName)) {
        throw "LogName cannot be null or empty."
    }

    # Define paths
    $LogPath = "$LogDirectory\$LogName.log"
    $ErrorLogPath = "$ErrorLogDirectory\Esi-Transcript_ErrorLog.txt"

    # Ensure directories exist
    if (-not (Test-Path -Path $ErrorLogDirectory)) {
        New-Item -Path $ErrorLogDirectory -ItemType Directory -Force | Out-Null
    }

    if (-not (Test-Path -Path $LogDirectory)) {
        New-Item -Path $LogDirectory -ItemType Directory -Force | Out-Null
    }

    # Function to log errors to a file
    function Log-ErrorToFile {
        param([string]$ErrorMessage)
        $Timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
        $LogMessage = "$Timestamp - $ErrorMessage"
        Add-Content -Path $ErrorLogPath -Value $LogMessage
    }

    # Check if a transcript is already running
    if ($global:TranscriptionStatus -eq $true) {
        Write-Warning "A transcript is already running. Stop the existing transcript before starting a new one."
        return
    }

    try {
        # Check if the log file exists
        if (-not (Test-Path -Path $LogPath)) {
            Write-Warning "Log file not found: $LogPath. A new file will be created when the transcript starts."
        } else {
            # Perform cleanup of old ZIP files
            $LogFileName = Split-Path -Path $LogPath -Leaf
            $ZipPattern = "$LogFileName.*.zip"

            Get-ChildItem -Path $LogDirectory -Filter $ZipPattern | ForEach-Object {
                try {
                    Remove-Item -Path $_.FullName -Force
                    Write-Output "Deleted old zip file: $($_.FullName)"
                } catch {
                    $ErrorMessage = "Failed to delete old zip file $($_.FullName): $_.Exception.Message"
                    Write-Warning $ErrorMessage
                    Log-ErrorToFile $ErrorMessage
                }
            }

            # Check the size of the log file
            $LogSizeMB = (Get-Item -Path $LogPath).Length / 1MB

            if ($LogSizeMB -gt $SizeThresholdMB) {
                # Compress the log file
                $CurrentDate = (Get-Date).ToString("dd.MM.yyyy")
                $DestinationPath = "$LogPath.$CurrentDate.zip"

                try {
                    Compress-Archive -Path $LogPath -DestinationPath $DestinationPath -Force
                    Write-Output "Log file compressed to: $DestinationPath"
                } catch {
                    $ErrorMessage = "Failed to compress the log file: $_.Exception.Message"
                    Write-Warning $ErrorMessage
                    Log-ErrorToFile $ErrorMessage
                }
            } else {
                Write-Output "Log size ($LogSizeMB MB) is within the threshold."
            }
        }

        # Start the transcript
        try {
            Start-Transcript -Append -Path $LogPath -ErrorAction Stop
            $global:TranscriptionStatus = $true
            Write-Output "Transcript started successfully at: $LogPath"
        } catch {
            $ErrorMessage = "Failed to start the transcript: $_.Exception.Message"
            Write-Warning $ErrorMessage
            Log-ErrorToFile $ErrorMessage
        }
    } catch {
        $ErrorMessage = "An unexpected error occurred: $_.Exception.Message"
        Write-Error $ErrorMessage
        Log-ErrorToFile $ErrorMessage
    }

    # Final output
    Write-Output "Script execution completed."
}