Home Forums Programming Powershell How to copy last line of .txt file into new .txt file? RE: How to copy last line of .txt file into new .txt file?

  • Thanks, opc.3. I'm sure there are better ways of doing this but reality is usually less perfect. What I came up with is the following:

    $fileEntries = [IO.Directory]::GetFiles("E:\datafiles");

    foreach($fileName in $fileEntries)

    {

    $d = $filename.EndsWith(".txt")

    IF($d)

    {

    $RowCount = Get-Content $FileName | Select-Object -last 1

    Add-Content "E:\DataFiles\SXRowCount.txt" ($fileName + '|' + $RowCount)

    }

    }

    It is inefficient to use Get-Content, but my files are relatively small. Apparently you used to be able to download a DOS translator for tail as part of the Windows Server toolkit but I don't find that anymore for 2008.

    Despite a brief delay, I end up with a file, SXRowCount.txt that has the file name and the last lines of all the files in the target directory. With this I can verify whether I've read in the correct number of rows and/or if the file completed normally.