PowerShell_unix PowerShell is definitely gaining momentum in the windows scripting world but I still hear folks wanting to rely on Unix based tools to get their job done.  In this series of posts I’m going to look at converting some of the more popular Unix based tools to PowerShell.

tail

The Unix “tail” command that is used to display the last 10 lines of each FILE to standard output.  With more than one file, precede each with a header giving the file name.  There is also a mode where it prints out the last “n” bytes in a file.  And for those that want to monitor changes to a file, there is the “follow” option where tail will monitor the file and print out any additions as they are made.

I’ve implemented these three options with the follow option only working on line mode.  The script could be made to work on byte mode as well, but I’ll leave that to the reader to implement if you really want it.

The unix parameters map to the following in my PowerShell script:

Unix PowerShell Description
-c -num_bytes Output the last N bytes.
-n -num_lines Output the last N lines (default 10).
-f -follow Output appended data as the file grows.
-s -sleep With “-f”, sleep for N seconds between iterations (default 1).
-q -quiet Never output headers giving file names.

The code will loop through the specified files.  For “num line” mode, it will get the contents of the file into a string array and print out the last “n” lines with the default being 10.  If the "-follow” switch was given, it will sit in a loop waiting the specified number of seconds before rechecking the file and if any modifications have been made it will print them to the console.  This is repeated indefinitely until the script is broken.

For byte mode, the content will be loaded into a string and the last “n” characters (up to the size of the file) will be displayed to the console.