SYS-CON MEDIA Authors: Liz McMillan, Carmen Gonzalez, Elizabeth White, Pat Romanski, Gary Arora

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
Concerns about security, downtime and latency, budgets, and general unfamiliarity with cloud technologies continue to create hesitation for many organizations that truly need to be developing a cloud strategy. Hybrid cloud solutions are helping to elevate those concerns by enabling the combination or orchestration of two or more platforms, including on-premise infrastructure, private clouds and/or third-party, public cloud services. This gives organizations more comfort to begin their digital tr...
Cloud Storage 2.0 has brought many innovations, including the availability of cloud storage services that are less expensive and much faster than previous generations of cloud storage. Cloud Storage 2.0 has also delivered new and faster methods for migrating your premises storage environment to the cloud and the concept of multi-cloud. This session will provide technical details on Cloud Storage 2.0 and the methods used to efficiently migrate from premises-to-cloud storage. This session will als...
In very short order, the term "Blockchain" has lost an incredible amount of meaning. With too many jumping on the bandwagon, the market is inundated with projects and use cases that miss the real potential of the technology. We have to begin removing Blockchain from the conversation and ground ourselves in the motivating principles of the technology itself; whether it is consumer privacy, data ownership, trust or even participation in the global economy, the world is faced with serious problems ...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It's clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Th...
For enterprises to maintain business competitiveness in the digital economy, IT modernization is required. And cloud, with its on-demand, elastic and scalable principles has resoundingly been identified as the infrastructure model capable of supporting fast-changing business requirements that enterprises are challenged with, as a result of our increasingly connected world. In fact, Gartner states that by 2022, 28% of enterprise IT spending will have shifted to cloud. But enterprises still must d...
Cloud-Native thinking and Serverless Computing are now the norm in financial services, manufacturing, telco, healthcare, transportation, energy, media, entertainment, retail and other consumer industries, as well as the public sector. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that pro...
The level of trust we have with individuals, businesses, and technology affects our lives daily. This is important to remember when discussing new technologies. For example, our level of trust is a critical factor when evaluating a new technology as a potential solution for providing business value. Given the importance of trust, imagine one's reaction upon hearing that blockchain is a "trustless trust" system. On the surface, that does sound like an oxymoron. This paper discusses how "trustless...
Public clouds dominate IT conversations but the next phase of cloud evolutions are "multi" hybrid cloud environments. The winners in the cloud services industry will be those organizations that understand how to leverage these technologies as complete service solutions for specific customer verticals. In turn, both business and IT actors throughout the enterprise will need to increase their engagement with multi-cloud deployments today while planning a technology strategy that will constitute a ...
Data center, on-premise, public-cloud, private-cloud, multi-cloud, hybrid-cloud, IoT, AI, edge, SaaS, PaaS... it's an availability, security, performance and integration nightmare even for the best of the best IT experts. Organizations realize the tremendous benefits of everything the digital transformation has to offer. Cloud adoption rates are increasing significantly, and IT budgets are morphing to follow suit. But distributing applications and infrastructure around increases risk, introdu...
Moving to Azure is the path to digital transformation, but not every journey is effective. Organizations that start with a cohesive, well-planned migration strategy can avoid common mistakes and stay a step ahead of the competition. Learn from Atmosera CEO, Jon Thomsen about the opportunities and challenges found in three pivotal phases of the journey to the cloud: Evaluation and Architecting, Migration and Management, and Optimization & Innovation. In each phase, there are distinct insights tha...
Most modern computer languages embed a lot of metadata in their application. We show how this goldmine of data from a runtime environment like production or staging can be used to increase profits. Adi conceptualized the Crosscode platform after spending over 25 years working for large enterprise companies like HP, Cisco, IBM, UHG and personally experiencing the challenges that prevent companies from quickly making changes to their technology, due to the complexity of their enterprise. An accomp...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
Andrew Keys is co-founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereum.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science" is responsible for guiding the technology strategy within Hitachi Vantara for IoT and Analytics. Bill brings a balanced business-technology approach that focuses on business outcomes to drive data, analytics and technology decisions that underpin an organization's digital transformation strategy. Bill has a very impressive background which includes ...