LogModule.psm1

<#
.SYNOPSIS
    Initializes logging for Intune app deployments.
 
.DESCRIPTION
    Sets up a logging folder and file under C:\ProgramData\IntuneApps\<AppName>\Logs, and provides Write-Log functionality.
 
.PARAMETER AppName
    The name of the application for which logs are being created.
 
.PARAMETER Context
    The deployment context: Install, Detect, or Uninstall.
 
.AUTHOR
    Brandon van Dijk <bdijk@uno.nl>
 
.COMPANY
    UNO
 
.DATE
    2025-07-30
 
.VERSION
    1.0.0
 
.NOTES
    Ensure the script runs with appropriate permissions to create folders and write files under C:\ProgramData.
#>

function Initialize-Logging {

    param (

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

        [Parameter(Mandatory=$true)][ValidateSet("Install","Detect","Uninstall")][string]$Context

    )
 
    # Context vastleggen

    $global:LogContext = $Context
 
    # Bepaal logpad

    $global:LogPath = "C:\ProgramData\IntuneApps\$AppName\Logs"

    Write-Host "[DEBUG] Initialize-Logging: LogPath = $global:LogPath"
 
    # Maak logs-folder aan (inclusief parents)

    if (-not (Test-Path -Path $global:LogPath)) {

        Write-Host "[DEBUG] Logs-folder bestaat niet; aanmaken"

        New-Item -Path $global:LogPath -ItemType Directory -Force | Out-Null

    }
 
    # Bepaal logbestand

    $fileName = "$(Get-Date -Format 'yyyy-MM-dd').log"

    $global:LogFile = Join-Path -Path $global:LogPath -ChildPath $fileName

    Write-Host "[DEBUG] Initialize-Logging: LogFile = $global:LogFile"
 
    # Schrijf startbericht

    Write-Log -Level INFO -Message "Logging gestart ($Context) voor $AppName"

}
 
function Write-Log {

    param (

        [Parameter(Mandatory=$true)][ValidateSet("INFO","WARN","ERROR")][string]$Level,

        [Parameter(Mandatory=$true)][string]$Message

    )
 
    $time = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'

    $ctx  = if ($global:LogContext) { "[$global:LogContext]" } else { "" }

    $line = "$time $ctx [$Level] $Message"
 
    Write-Host $line

    if ($global:LogFile) {

        try {

            Add-Content -Path $global:LogFile -Value $line

        } catch {

            Write-Host "[ERROR] Fout bij schrijven naar logbestand: $_"

        }

    }

}