Very often Administrators has the task to monitor log file like windows log file, iis log, error log, firewall log file and get last x of lines from file. In PowerShell tail parameter of Get-Content cmdlet is Unix tail equivalent command used to monitor the file and get last lines of the file.
Using PowerShell, administrators can easily get tail of the file using Get-Content cmdlet which has a tail parameter.
In PowerShell tail parameter specifies the number of the lines from the end of the file. You can also use tail alias
Let’s understand using Get-Content tail examples to read end of the file, a file can be iis log file, windows event log, firewall log, or any other file.
Cool Tip: How to get certificates using PowerShell!
Using PowerShell tail of Window Event log
To get the last 10 lines of the Windows Event log, use the below Get-Content tail parameter.
Get-Content "C:\PowerShell\EventLog_Setup.txt" -tail 3
The above get-content tail command output show the last 3 lines of the file.
PowerShell tail – Show last line of the file
To get last line of the file, use tail parameter with the value 1. Here -tail 1 show the bottom line of the file
Get-Content "C:\PowerShell\EventLog_Setup.txt" -tail 1
Cool Tip: Do you know the equivalent of cat command in Windows!
Get tail of the big file and export to csv
Often administrators need to extract few lines from the big log file to analyze the log data.
To get tail of last 50 lines of big file and export it csv file, use the below command
Get-Content "C:\PowerShell\EventLog_Setup.txt" -tail 50 | Out-File -FilePath "C:\PowerShell\output.csv"
In the above command, PowerShell Get-Content cmdlet -tail parameter gets last 50 lines of the code. Using pipe operator, it passed extracted lines to Out-File for export to csv file.
Cool Tip: Using PowerShell to get first line of file!
Using wait parameter to display new line
Another popular use of tail parameter is to get last lines from the file. Using Get-Content cmdlet -wait parameter, it keeps the file open after all existing lines output to console and watch the new line after every one second.
Get-Content "C:\PowerShell\iislog.txt" -wait
you can stop the waiting using Ctrl + C
Cool Tip: Learn how to get aduser using userprincipalname!
In the above blog post, I have explained how to get last lines of the file using Get-Content tail parameter. In PowerShell tail parameter is very useful to get specific number of lines from the file.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on ShellGeek home page.