This repository has been archived on 2023-10-10. You can view files and clone it, but cannot push or open issues or pull requests.
DroneHelper/src/FileLinter/Test-FileEncoding.ps1
OCram85 8fd180b776
Some checks reported errors
continuous-integration/drone/tag Build was killed
initial migration
2022-07-13 13:59:25 +02:00

74 lines
1.8 KiB
PowerShell

function Test-FileEncoding {
<#
.SYNOPSIS
Returns true if the given file is written in a valid encoding
.DESCRIPTION
Test the given file against the encoding regex and returns true or false
.PARAMETER Path
Relative or full path to an existing file.
.PARAMETER Encoding
Optional custom encoding regex string. Default is (utf8|ascii|xml).
.INPUTS
[none]
.OUTPUTS
[bool]
.EXAMPLE
Test-FileEncoding -Path './testfile.txt'
.NOTES
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingInvokeExpression',
'',
Justification = 'static input without user manipulation'
)]
[OutputType([bool])]
param (
[Parameter(Mandatory = $true)]
[ValidateScript(
{
Test-Path -Path $_
}
)]
[string]$Path,
[Parameter(Mandatory = $false)]
[string]$Encoding = '(utf8|utf-8|ascii|xml)'
)
begin {
}
process {
try {
Get-Command -Name 'file' -ErrorAction 'Stop' | Out-Null
}
catch {
Write-Error -Message "Could not find command called 'file'!" -ErrorAction 'Stop'
}
$Res = Invoke-Expression -Command ("file '{0}' " -f $Path)
# Remove the file from matching. Use the latest array element if split doesn't work.
$ParsedResult = ($Res -split ':')[-1]
Write-Debug -Message ('Encoding: Raw file output {0}' -f $Res)
Write-Debug -Message ('Parsed match string: {0}' -f $ParsedResult)
if ($ParsedResult -match $Encoding) {
Write-Output $true
}
else {
Write-Output $false
}
}
end {
}
}