Private/Test-Utf8Bom.ps1
|
<# .SYNOPSIS Tests whether a file starts with the UTF-8 byte order mark (EF BB BF). .DESCRIPTION Reads only the first three bytes of the file with Get-Content, so it works in Constrained Language Mode on Windows PowerShell 5.1 and PowerShell 7. Returns $false for missing, empty or shorter files. .PARAMETER Path The file to test. .OUTPUTS System.Boolean. #> function Test-Utf8Bom { [CmdletBinding()] [OutputType([bool])] param( [Parameter(Mandatory = $true)] [string]$Path ) if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false } if ($PSVersionTable.PSEdition -eq 'Core') { $bytes = @(Get-Content -LiteralPath $Path -AsByteStream -TotalCount 3 -ErrorAction Stop) } else { $bytes = @(Get-Content -LiteralPath $Path -Encoding Byte -TotalCount 3 -ErrorAction Stop) } return ($bytes.Count -eq 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) } |