Private/Test/Test-IsUtf8.ps1
|
function Test-IsUtf8 { <# .SYNOPSIS Tests if the console output encoding is set to UTF-8. .DESCRIPTION Checks if the current console output encoding is UTF-8 by verifying the CodePage is set to 65001 (the universal UTF-8 code page identifier). UTF-8 encoding is important for proper display of international characters, emojis, and special symbols in console output. This function helps determine if the console is properly configured for Unicode output. .INPUTS None. This function does not accept pipeline input. .OUTPUTS System.Boolean Returns $true if the console output encoding is UTF-8 (CodePage 65001). Returns $false if using a different encoding. .EXAMPLE Test-IsUtf8 Returns $true if the console output encoding is UTF-8. .EXAMPLE if (-not (Test-IsUtf8)) { Write-Warning "UTF-8 encoding is not enabled. Setting UTF-8..." [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } Enables UTF-8 encoding if not already set. .EXAMPLE if (Test-IsUtf8) { Write-Host "✓ UTF-8 is enabled - special characters will display correctly" } Uses UTF-8 characters when encoding is properly configured. .NOTES CodePage 65001 is the universal identifier for UTF-8 encoding across all systems. This is more reliable than checking the EncodingName property which can vary by locale. To manually set UTF-8 encoding: [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 .LINK https://learn.microsoft.com/en-us/dotnet/api/system.console.outputencoding .LINK https://learn.microsoft.com/en-us/windows/console/console-code-pages #> [CmdletBinding()] [OutputType([bool])] param ( ) #requires -Version 5.1 try { # CodePage 65001 = UTF-8 (universal identifier) $CodePage = 65001 $currentCodePage = [Console]::OutputEncoding.CodePage $result = ($currentCodePage -eq $CodePage) Write-Verbose "Checking UTF-8 encoding: Current CodePage is $currentCodePage, expected $CodePage. Result: $result" $result } catch { $errorRecord = [System.Management.Automation.ErrorRecord]::new( $_.Exception, 'EncodingCheckFailed', [System.Management.Automation.ErrorCategory]::NotSpecified, $null ) $PSCmdlet.WriteError($errorRecord) return $false } } |