Welcome!

Blog Feed Post

Unix To PowerShell - Tail

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.

   1: #----------------------------------------------------------------
   2: # Tail.ps1
   3: #----------------------------------------------------------------
   4: param
   5: (
   6:     [string]$filespec = $null,
   7:     [int]$num_bytes = -1,
   8:     [int]$num_lines = -1,
   9:     [bool]$follow = $false,
  10:     [int]$sleep = 1,
  11:     [bool]$quiet = $false
  12: );
  13:  
  14: function Do-Tail()
  15: {
  16:     param
  17:     (
  18:         [string]$filespec = $null,
  19:         [int]$num_bytes = -1,
  20:         [int]$num_lines = -1,
  21:         [bool]$follow = $false,
  22:         [int]$sleep = 1,
  23:         [bool]$quiet = $false
  24:     );
  25:     
  26:     # if no bytes or lines specified, default to 10 lines
  27:     if ( (-1 -eq $num_bytes) -and (-1 -eq $num_lines) ) { $num_lines = 10; }
  28:     
  29:     $files = @(Get-ChildItem $filespec);
  30:     foreach ($file in $files)
  31:     {
  32:         # Optionally output file names when multiple files given
  33:         if ( ($files.Length -gt 1) -and !$quiet ) { Write-Host "==> $($file.Name) <=="; }
  34:     
  35:         if ( -1 -ne $num_lines )
  36:         {
  37:             $prev_len = 0;
  38:             while ($true)
  39:             {
  40:                 # For line number option, get content as an array of lines
  41:                 # and print out the last "n" of them.
  42:                 $lines = Get-Content $file;
  43:                 
  44:                 if ( $prev_len -ne 0 ) { $num_lines = $lines.Length - $prev_len; }
  45:                 
  46:                 $start_line = $lines.Length - $num_lines;
  47:                 
  48:                 # Ensure that we don't go past the beginning of the input
  49:                 if ( $start_line -le 0 ) { $start_line = 0; }
  50:                 
  51:                 for ($i = $start_line; $i -lt $lines.Length; $i++)
  52:                 {
  53:                     $lines[$i];
  54:                 }
  55:                 $prev_len = $lines.Length;
  56:                 
  57:                 # If we are following the file, sleep the desired interval
  58:                 # else break out of the loop and continue with the next file.
  59:                 if ( $follow )
  60:                 {
  61:                     Start-Sleep $sleep;
  62:                 }
  63:                 else
  64:                 {
  65:                     break;
  66:                 }
  67:             }
  68:         }
  69:         elseif ( -1 -ne $num_bytes )
  70:         {
  71:             # for num bytes option, get the content as a single string 
  72:             # and substring the last "n" bytes.
  73:             [string]$content = Get-Content $file -delim [char]0;
  74:             
  75:             if ( ($content.Length - $num_bytes) -lt 0 ) { $num_bytes = $content.Length; }
  76:             $content.SubString($content.Length - $num_bytes);
  77:         }
  78:     }
  79: }
  80:  
  81: Do-Tail -filespec $filespec -num_bytes $num_bytes -num_lines $num_lines `
  82:     -follow $follow -sleep $sleep -quiet $quiet;

 

Download the source for the script here: Tail.ps1

 

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

Latest Stories
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
Enterprises are moving to the cloud faster than most of us in security expected. CIOs are going from 0 to 100 in cloud adoption and leaving security teams in the dust. Once cloud is part of an enterprise stack, it’s unclear who has responsibility for the protection of applications, services, and data. When cloud breaches occur, whether active compromise or a publicly accessible database, the blame must fall on both service providers and users. In his session at 21st Cloud Expo, Ben Johnson, C...
Most of the time there is a lot of work involved to move to the cloud, and most of that isn't really related to AWS or Azure or Google Cloud. Before we talk about public cloud vendors and DevOps tools, there are usually several technical and non-technical challenges that are connected to it and that every company needs to solve to move to the cloud. In his session at 21st Cloud Expo, Stefano Bellasio, CEO and founder of Cloud Academy Inc., will discuss what the tools, disciplines, and cultural...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
With the rise of DevOps, containers are at the brink of becoming a pervasive technology in Enterprise IT to accelerate application delivery for the business. When it comes to adopting containers in the enterprise, security is the highest adoption barrier. Is your organization ready to address the security risks with containers for your DevOps environment? In his session at @DevOpsSummit at 21st Cloud Expo, Chris Van Tuin, Chief Technologist, NA West at Red Hat, will discuss: The top security r...
IBM helps FinTechs and financial services companies build and monetize cognitive-enabled financial services apps quickly and at scale. Hosted on IBM Bluemix, IBM’s platform builds in customer insights, regulatory compliance analytics and security to help reduce development time and testing. In his session at 21st Cloud Expo, Lennart Frantzell, a Developer Advocate with IBM, will discuss how these tools simplify the time-consuming tasks of selection, mapping and data integration, allowing devel...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
Today traditional IT approaches leverage well-architected compute/networking domains to control what applications can access what data, and how. DevOps includes rapid application development/deployment leveraging concepts like containerization, third-party sourced applications and databases. Such applications need access to production data for its test and iteration cycles. Data Security? That sounds like a roadblock to DevOps vs. protecting the crown jewels to those in IT.
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...