Start-IntuneRemediationTranscript.psm1

function Start-IntuneRemediationTranscript {
    [CmdletBinding()]
    param(
        [string]$LogName,
        [int]$SizeThresholdMB = 5,
        [switch]$Stop
    )

    # Define paths
    $LogPath = "$env:HomeDrive\ProgramData\Microsoft\IntuneManagementExtension\Logs\$($LogName).log"
    $ErrorLogDirectory = "$env:ProgramData\ErrorLogs"
    $ErrorLogPath = "$ErrorLogDirectory\Esi-Transcript_ErrorLog.txt"

    # Ensure the error log directory exists
    if (-not (Test-Path -Path $ErrorLogDirectory)) {
        New-Item -Path $ErrorLogDirectory -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
    }

    # Handle stopping the transcript
    if ($Stop) {
        try {
            Stop-Transcript
            Write-Output "Transcript stopped successfully."
        } catch {
            $errorMessage = "No transcript is active or an error occurred while stopping the transcript: $_"
            Write-Warning $errorMessage
            Log-ErrorToFile $errorMessage
        }
        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
            $LogDirectory = Split-Path -Path $LogPath -Parent
            $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): $_"
                    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: $_"
                    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
        } catch {
            $errorMessage = "Failed to start the transcript: $_"
            Write-Warning $errorMessage
            Log-ErrorToFile $errorMessage
        }
    } catch {
        $errorMessage = "An unexpected error occurred: $_"
        Write-Error $errorMessage
        Log-ErrorToFile $errorMessage
    }

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