Reputation: 18848
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
Upvotes: 3
Views: 2179
Reputation: 26170
You could use a FileSystemWatcher
object and the Register-ObjectEvent
cmdlet to monitor changes made to the filesystem. Something like this :
$fw = New-Object System.IO.FileSystemWatcher
$fw.Path = "C:\temp\events\test"
Register-ObjectEvent -InputObject $fw -EventName Changed -SourceIdentifier File.Changed -Action {
#$event
write-host "file changed : $($event.SourceEventArgs.Name)"
get-content $event.SourceEventArgs.fullpath -tail 5 |out-host
} |out-null
#unregister event when done
#Unregister-Event -SourceIdentifier file.changed
Upvotes: 0
Reputation: 1323
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
Upvotes: 5