Skip to content

Instantly share code, notes, and snippets.

@joshooaj
Last active May 29, 2025 21:16
Show Gist options
  • Save joshooaj/1b4f3e57f9e1e0474918b5de7cc68e20 to your computer and use it in GitHub Desktop.
Save joshooaj/1b4f3e57f9e1e0474918b5de7cc68e20 to your computer and use it in GitHub Desktop.
Find files with specific line endings or mixed line endings
function Get-LineEnding {
<#
.SYNOPSIS
Returns the line ending found in a given file.
.DESCRIPTION
Returns a [PSCustomObject] with a `LineEnding` property with the value
'CRLF', 'LF', or 'MIXED' depending on the line endings found in the file.
.EXAMPLE
Get-ChildItem *.ps1 -Recurse | Get-LineEnding | Where-Object LineEnding -eq 'MIXED'
Returns any .PS1 file in the current directory or any subdirectory where
there are a mix of CRLF and LF line endings.
.NOTES
This function does not distinguish between text and binary files, and it
reads files byte by byte, so you should take care not to pass in paths of
large binary files.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string]
$Path,
[Parameter()]
[Switch]
$ResolveRelativePath
)
begin {
$CR, $LF = [byte[]](13, 10)
}
process {
$pathParams = @{
Path = $Path
ErrorAction = 'Stop'
}
if ($ResolveRelativePath) {
$pathParams.Relative = $true
}
$Path = [string](Resolve-Path @pathParams)
if (-not (Test-Path -Path $Path -PathType Leaf)) {
Write-Error "The path '$Path' does not exist or is not a file."
return
}
$lineEnding = $null
try {
$lastByte = [byte]0
$fs = [io.file]::OpenRead($Path)
while ($fs.Position -lt $fs.Length) {
$byte = $fs.ReadByte()
if ($byte -eq $LF) {
if ($lastByte -eq $CR) {
if ($lineEnding -eq 'LF') {
$lineEnding = 'MIXED'
break
}
$lineEnding = 'CRLF'
} else {
if ($lineEnding -eq 'CRLF') {
$lineEnding = 'MIXED'
break
}
$lineEnding = 'LF'
}
}
$lastByte = $byte
}
[pscustomobject]@{
Path = $Path
LineEnding = $lineEnding
}
} finally {
$fs.Dispose()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment