functions/filesystem/Test-IsUtf8WithBom.ps1

function Test-IsUtf8WithBom {
<#
.SYNOPSIS
Prüft, ob eine Datei im UTF-8-Format mit Byte Order Mark (BOM) gespeichert ist.
 
.DESCRIPTION
Diese Funktion liest die ersten drei Bytes einer Datei und prüft, ob sie dem UTF-8 BOM entsprechen (EF BB BF).
Sie gibt $true zurück, wenn die Datei UTF-8 mit BOM ist, andernfalls $false.
 
.PARAMETER Path
Der Pfad zur Datei, die überprüft werden soll. Muss eine vorhandene Datei sein.
 
.INPUTS
System.String
 
.OUTPUTS
System.Boolean
 
.EXAMPLE
Test-IsUtf8WithBom -Path ".\script.ps1"
 
Gibt $true zurück, wenn die Datei UTF-8 mit BOM ist, andernfalls $false.
 
.EXAMPLE
Get-ChildItem -Recurse -Filter *.ps1 | ForEach-Object { Test-IsUtf8WithBom -Path $_.FullName }
 
Prüft rekursiv alle PS1-Dateien in einem Verzeichnisbaum auf UTF-8 mit BOM.
 
.NOTES
Autor: Dein Name
Letzte Änderung: 08.06.2025
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string] $Path
    )

    process {
        if (-not (Test-Path $Path)) {
            Write-Error "File not found: $Path"
            return $false
        }

        try {
            $fs = [System.IO.File]::OpenRead($Path)
            $bytes = New-Object byte[] 3
            $fs.Read($bytes, 0, 3) | Out-Null
            $fs.Close()

            return ($bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF)

        } catch {
            Write-Error "Error reading file $($Path): $_"
            return $false
        }

        return $true
    }
}