SYS-CON MEDIA Authors: Zakia Bouachraoui, Liz McMillan, Yeshim Deniz, Janakiram MSV, Carmen Gonzalez

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.


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: );
  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:     );
  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; }
  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) <=="; }
  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;
  44:                 if ( $prev_len -ne 0 ) { $num_lines = $lines.Length - $prev_len; }
  46:                 $start_line = $lines.Length - $num_lines;
  48:                 # Ensure that we don't go past the beginning of the input
  49:                 if ( $start_line -le 0 ) { $start_line = 0; }
  51:                 for ($i = $start_line; $i -lt $lines.Length; $i++)
  52:                 {
  53:                     $lines[$i];
  54:                 }
  55:                 $prev_len = $lines.Length;
  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;
  75:             if ( ($content.Length - $num_bytes) -lt 0 ) { $num_bytes = $content.Length; }
  76:             $content.SubString($content.Length - $num_bytes);
  77:         }
  78:     }
  79: }
  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
In an age of borderless networks, security for the cloud and security for the corporate network can no longer be separated. Security teams are now presented with the challenge of monitoring and controlling access to these cloud environments, at the same time that developers quickly spin up new cloud instances and executives push forwards new initiatives. The vulnerabilities created by migration to the cloud, such as misconfigurations and compromised credentials, require that security teams t...
Cloud is the motor for innovation and digital transformation. CIOs will run 25% of total application workloads in the cloud by the end of 2018, based on recent Morgan Stanley report. Having the right enterprise cloud strategy in place, often in a multi cloud environment, also helps companies become a more intelligent business. Companies that master this path have something in common: they create a culture of continuous innovation. In his presentation, Dilipkumar Khandelwal outlined the latest...
The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...
The use of containers by developers -- and now increasingly IT operators -- has grown from infatuation to deep and abiding love. But as with any long-term affair, the honeymoon soon leads to needing to live well together ... and maybe even getting some relationship help along the way. And so it goes with container orchestration and automation solutions, which are rapidly emerging as the means to maintain the bliss between rapid container adoption and broad container use among multiple cloud host...
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like "How is my application doing" but no id...
The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
Is advanced scheduling in Kubernetes achievable?Yes, however, how do you properly accommodate every real-life scenario that a Kubernetes user might encounter? How do you leverage advanced scheduling techniques to shape and describe each scenario in easy-to-use rules and configurations? In his session at @DevOpsSummit at 21st Cloud Expo, Oleg Chunikhin, CTO at Kublr, answered these questions and demonstrated techniques for implementing advanced scheduling. For example, using spot instances and co...
Platform-as-a-Service (PaaS) is a technology designed to make DevOps easier and allow developers to focus on application development. The PaaS takes care of provisioning, scaling, HA, and other cloud management aspects. Apache Stratos is a PaaS codebase developed in Apache and designed to create a highly productive developer environment while also supporting powerful deployment options. Integration with the Docker platform, CoreOS Linux distribution, and Kubernetes container management system ...
Because Linkerd is a transparent proxy that runs alongside your application, there are no code changes required. It even comes with Prometheus to store the metrics for you and pre-built Grafana dashboards to show exactly what is important for your services - success rate, latency, and throughput. In this session, we'll explain what Linkerd provides for you, demo the installation of Linkerd on Kubernetes and debug a real world problem. We will also dig into what functionality you can build on ...
DevOps is a world surrounded by information, starting from a single commit and ending in roll out to production. In this talk, I'll introduce you to the world of Taboola DevOps data collection, to better understand what goes on under the hood. The system we've developed in-house helps us collect and analyse the entire DevOps process from the very first commit all the way to production. It provides us a full clear view with a drill-down toolset that helps keep us away from the dark side. ...
In his session at 20th Cloud Expo, Mike Johnston, an infrastructure engineer at, will discuss how to use Kubernetes to setup a SaaS infrastructure for your business. Mike Johnston is an infrastructure engineer at with over 12 years of experience designing, deploying, and maintaining server and workstation infrastructure at all scales. He has experience with brick and mortar data centers as well as cloud providers like Digital Ocean, Amazon Web Services, and Rackspace....
After years of investments and acquisitions, CloudBlue was created with the goal of building the world's only hyperscale digital platform with an increasingly infinite ecosystem and proven go-to-market services. The result? An unmatched platform that helps customers streamline cloud operations, save time and money, and revolutionize their businesses overnight. Today, the platform operates in more than 45 countries and powers more than 200 of the world's largest cloud marketplaces, managing mo...
Containerized software is riding a wave of growth, according to latest RightScale survey. At Sematext we see this growth trend via our Docker monitoring adoption and via Sematext Docker Agent popularity on Docker Hub, where it crossed 1M+ pulls line. This rapid rise of containers now makes Docker the top DevOps tool among those included in RightScale survey. Overall Docker adoption surged to 35 percent, while Kubernetes adoption doubled, going from 7% in 2016 to 14% percent.
The Crypto community has run out of anarchists, libertarians and almost absorbed all the speculators it can handle, the next 100m users to join Crypto need a world class application to use. What will it be? Alex Mashinsky, a 7X founder & CEO of Celsius Network will discuss his view of the future of Crypto.
In an age of borderless networks, security for the cloud and security for the corporate network can no longer be separated. Security teams are now presented with the challenge of monitoring and controlling access to these cloud environments, as they represent yet another frontier for cyber-attacks. Complete visibility has never been more important-or more difficult. Powered by AI, Darktrace's Enterprise Immune System technology is the only solution to offer real-time visibility and insight into ...