Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# EOL converter
function convertEOL
{
<#
.SYNOPSIS
Function to convert Windows EOL to Unix EOL format.
.DESCRIPTION
Takes EOL format and file as input and converts the entire file to provided EOL format.
.NOTES
Change the line endings of a text file to: Windows (CR/LF), Unix (LF) or Mac (CR)
Requires PowerShell 3.0 or greater
.EXAMPLE
convertEOL -lineEnding <mac|unix|win> -file <full path to file>
convertEOL -lineEnding unix -file "$scriptPath\$fileBase\$fileBase.ansibleInventory.txt"
.LINK
Source https://ss64.com/ps/syntax-set-eol.html
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[ValidateSet("mac","unix","win")]
[string]$lineEnding,
[Parameter(Mandatory=$True)]
[string]$file
)
# Convert the friendly name into a PowerShell EOL character
Switch ($lineEnding) {
"mac" { $eol="`r" }
"unix" { $eol="`n" }
"win" { $eol="`r`n" }
}
# Replace CR+LF with LF
$text = [System.IO.File]::ReadAllText($file) -replace "`r`n", "`n"
[System.IO.File]::WriteAllText($file, $text)
# Replace CR with LF
$text = [System.IO.File]::ReadAllText($file) -replace "`r", "`n"
[System.IO.File]::WriteAllText($file, $text)
# At this point all line-endings should be LF.
# Replace LF with intended EOL char
if ($eol -ne "`n") {
$text = [System.IO.File]::ReadAllText($file) -replace "`n", $eol
[System.IO.File]::WriteAllText($file, $text)
}
return "True"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment