Search code examples
powershelltail

Powershell cmd to Tail over the files of Directory


I am looking for Powershell cmd to print the last 5 lines of data from any file in the directory.

Ideally

Get-Content -Tail 5 -Wait .\test.log

will print tail over the specific file from last 5 lines. If any new content is being appended to that file, it will keep printing.

Similarly, I want to tail over all the files from directory. Print the contents if any file is getting modified.

Tried something like this, didn't work!

Get-Content -Tail 5 -Wait .\folder*.log


Solution

  • While you can use -Tail with multiple files, when using -Wait only the first file will have it changes reported. But this is possible if you use a workflow and run the command in parallel.

    # Get-Tail.ps1
    Workflow Get-Tail
    {
        param (
            [string[]]$Path,
            [int]$Tail
        )
    
        foreach -parallel ($File in $Path) {
            Get-Content -Path $File -Tail $Tail -Wait
        }
    }
    

    Then run the following:

    . .\Get-Tail.ps1
    $files = (dir .\folder*.log).FullName
    Get-Tail -Path $files -Tail 5