Search code examples
powershellpowershell-3.0

Powershell 3: Remove last line of text file


I am using the following script to iterate through a list of files in a folder, then it will regex search for a string containing the 'T|0-9' which is the trailer record and will be present at the end of each text file.

$path = "D:\Test\"
$filter =  "*.txt"
$files = Get-ChildItem -path $path -filter $filter

foreach ($item in $files)

{
            $search = Get-content $path$item
            ($search)| ForEach-Object { $_ -replace 'T\|[0-9]*', '' } | Set-Content $path$item

}

This script works fine, however, it may take a long time to go through large file, I therefore used the '-tail 5' parameter so that it will start searching from the last 5 lines, the problem is that it is deleting everything and only leaving the last lines in the feed.

Is there any other way to acomplish this?

I tried another sample code I found but it doesnt really work, can someone guide me please

$stream = [IO.File]::OpenWrite($path$item)
$stream.SetLength($stream.Length - 2)
$stream.Close()
$stream.Dispose()

Solution

  • Since Get-Content returns an array, you can access the last item (last line) using [-1]:

    foreach ($item in $files)
    {
        $search = Get-content $item.FullName
        $search[-1] = $search[-1] -replace 'T\|[0-9]*', ''
        $search | Set-Content $item.FullName
    }