powershellnewlineeol

Is there a Powershell command that will print a specified file's EOL characters?


I have four text files in the following directory that have varying EOL characters:

C:\Sandbox 1.txt, 2.txt, 3.txt, 4.txt

I would like to write a powershell script that will loop through all files in the directory and find the EOL characters that are being used for each file and print them into a new file named EOL.txt

Sample contents of EOL.txt:

1.txt UNIX(LF)
2.txt WINDOWS(CRLF)
3.txt WINDOWS(CRLF)
4.txt UNIX(LF)

I know to loop through files I will need something like the following, but I'm not sure how to read the file EOL:

Get-ChildItem "C:\Sandbox" -Filter *.txt | 
Foreach-Object {
}

OR

Get-Content "C:\Sandbox\*"  -EOL | Out-File -FilePath "C:\Sandbox\EOL.txt"
##note that EOL is not a valid Get-Content command

Solution

  • Try the following:

    Get-ChildItem C:\Sandbox\*.txt -Exclude EOL.txt |
      Get-Content -Raw |
        ForEach-Object {
          $newlines = [regex]::Matches($_, '\r?\n').Value | Select-Object -Unique
          $newLineDescr = 
            switch ($newlines.Count) {
              0 { 'N/A' }
              2 { 'MIXED' }
              default { ('UNIX(LF)', 'WINDOWS(CRLF)')[$newlines -eq "`r`n"] }
            }
          # Construct and output a custom object for the file at hand.
          [pscustomobject] @{
            Path          = $_.PSChildName
            NewlineFormat = $newLineDescr
          }
        } # | Out-File ... to save to a file - see comments below.
    

    The above outputs something like:

    FileName NewlineFormat
    -------- -------------
    1.txt    UNIX(LF)
    2.txt    WINDOWS(CRLF)
    3.txt    N/A
    4.txt    MIXED
    

    N/A means that no newlines are present, MIXED means that both CRLF and LF newlines are present.

    You can save the output:

    Note:


    Simpler alternative via WSL, if installed:

    WSL comes with the file utility, which analyzes the content of files and reports summary information, including newline formats.

    While you get no control over the output format, which invariably includes additional information, such as the file's character encoding, the command is much simpler:

    Set-Location C:\Sandbox
    wsl file *.txt
    

    Caveats:

    Interpreting the output: