Skip to content

Instantly share code, notes, and snippets.

@leblocks
Last active February 2, 2024 18:18
Show Gist options
  • Save leblocks/e239b36a0a8e0164846b46d37e04c827 to your computer and use it in GitHub Desktop.
Save leblocks/e239b36a0a8e0164846b46d37e04c827 to your computer and use it in GitHub Desktop.
multi file tail for powershell core
<#
.SYNOPSIS
Watches text files for changes and prints the specified number of lines from the end of the file.
.DESCRIPTION
This function monitors a set of text files for changes and prints the content to the console.
Each line printed is prefixed by the filename.
.PARAMETER Paths
An array of paths to text files to monitor. This parameter is mandatory.
.PARAMETER Tail
Number of lines to print from the end of each file initially.
.PARAMETER ThrottleLimit
Limits the number of script blocks running in parallel.
By default, it is set to the number of paths passed.
.EXAMPLE
Watch-Files -Paths "C:\File1.txt", "C:\File2.txt" -Tail 10
# watching files in a path by a glob
Write-Output (Get-ChildItem *.txt) -NoEnumerate | Watch-Files
#>
function Watch-Files {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string[]] $Paths,
[int] $Tail = 10,
[int] $ThrottleLimit
)
if ($ThrottleLimit -eq 0) {
$ThrottleLimit = $Paths.Length
}
$Paths |
ForEach-Object -Parallel {
$path = $_;
$fileName = (Get-ChildItem $path).Name
Get-Content -Wait -Tail $($using:Tail) -Path $path
| ForEach-Object {
$colors = [Enum]::GetNames([System.ConsoleColor])
| Select-Object -Skip 1
$index = [array]::IndexOf($($using:Paths), $path)
$color = $colors[$index % $colors.Length]
Write-Host "[$fileName] " -NoNewLine -ForegroundColor $color
Write-Host ${_}
}
} -ThrottleLimit $ThrottleLimit
}
@leblocks
Copy link
Author

leblocks commented Jan 31, 2024

Multi file tail for powershell core

  • Based on a blogpost by Chad Baldwin

  • Usage:

    • Provide paths manually:

      Watch-Files -Paths "C:\File1.txt", "C:\File2.txt"
      Watch-Files -Paths "C:\File1.txt", "C:\File2.txt" -Tail 10
    • Paths from a pipeline:
      Stuff with Write-Output is needed to pack gci results into an array, so Watch-Files gets them all at once.
      By default -ThrottleLimit is set to amount of files passed.

      Write-Output (gci *.log) -NoEnumerate | Watch-Files
  • Demo:
    watch_files_example2|150x200

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment