Blog Feed Post

Unix To PowerShell - Seq

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 “seq” command prints a sequence of numbers from FIRST to LAST, in steps of INCREMENT.

The PowerShell “range” operator “..” will return an array of numbers but it does not give you the ability to modify the increment from 1 (or –1 if the LAST is smaller than FIRST).  I accomplished this with a simple for loop.  Since the comparison needed to be “less than or equal” for a increasing sequence and “greater than or equal” for a decreasing sequence, I executed the “for” loop with the Invoke-Expression command setting the comparison operator with a variable.  This avoided having to code two different for loops. 

Next, if the “equal width” argument is true, the max width is calculated from the FIRST and LAST numbers and the generated array is iterated through, modifying the entries if their widths were below the maximum.

Finally the array is either converted to a string with the supplied separator, or displayed to the console with entries separated by newlines.

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

Unix PowerShell Description
-s -separator Use STRING to separate numbers (default crlf).
-w -equal_width equalize width by padding with leading zeros.
FIRST -first The start of the sequence.
INCREMENT -increment The steps between items.
LAST -last The end of the sequence.


   1: #----------------------------------------------------------------
   2: # Seq.ps1
   3: #----------------------------------------------------------------
   4: param
   5: (
   6:   [string]$filespec = $null,
   7:   [string]$separator = "",
   8:   [bool]$equal_width = $false,
   9:   [int]$first = $null,
  10:   [int]$last = $null,
  11:   [int]$increment = $null
  12: );
  14: #----------------------------------------------------------------
  15: # function Get-NumberWidth
  16: #----------------------------------------------------------------
  17: function Get-NumberWidth()
  18: {
  19:   param([int]$n = $null);
  20:   ([string]$n).Length;
  21: }
  23: #----------------------------------------------------------------
  24: # function Do-Seq
  25: #----------------------------------------------------------------
  26: function Do-Seq()
  27: {
  28:   param
  29:   (
  30:     [string]$filespec = $null,
  31:     [string]$separator = "",
  32:     [bool]$equal_width = $false,
  33:     [int]$first = $null,
  34:     [int]$last = $null,
  35:     [int]$increment = $null
  36:   );
  38:   if ( !$increment )
  39:   {
  40:     $increment = 1;
  41:     if ( $last -lt $first ) { $increment = -1; }
  42:   }
  43:   else
  44:   {
  45:     if ( ($first -gt $last) -and ($increment -ge 0) )
  46:     {
  47:       Write-Host `
  48:         "When the starting value is larger than the limit, the increment must be negative.";
  49:       exit;
  50:     }
  51:     elseif ( ($last -gt $first) -and ($increment -le 0) )
  52:     {
  53:       Write-Host `
  54:         "When the starting value is smaller than the limit, the increment must be positive.";
  55:       exit;
  56:     }
  57:   }
  59:   $seq = @();
  61:   $compare = "-ge";
  62:   if ( $last -ge $first ) { $compare = "-le"; }
  64:   Invoke-Expression "for(`$i = `$first; `$i $compare `$last; `$i += `$increment) { `$seq += @(`$i); }";
  66:   if ( $equal_width )
  67:   {
  68:     # determine the max width needed.
  69:     $first_width = (Get-NumberWidth $first);
  70:     $last_width = (Get-NumberWidth $last);
  71:     if ( $first_width -gt $last_width )
  72:     {
  73:       $max_width = $first_width;
  74:     }
  75:     else
  76:     {
  77:       $max_width = $last_width;
  78:     }
  80:     # Iterate through the array and pad numbers to max width
  81:     for($i=0; $i -lt $seq.Length; $i++)
  82:     {
  83:       if ( (Get-NumberWidth $seq[$i]) -lt $max_width )
  84:       {
  85:         $mult = $max_width;
  86:         if ( $seq[$i] -lt 0 ) { $mult--; }
  87:         $seq[$i] = "{0,0:$(""0""*$mult)}" -f $seq[$i];
  88:       }
  89:     }
  90:   }
  92:   # If a separator was specified, then use it,
  93:   # otherwise default to newlines.
  94:   if ( $separator )
  95:   {
  96:     [string]::Join($separator, $seq);
  97:   }
  98:   else
  99:   {
 100:     $seq;
 101:   }
 103: }
 105: if ( !$first -and !$last )
 106: {
 107:   Write-Host @"
 108:   Usage: Seq.ps1 [arguments]
 109:     -separator STRING - use STRING to separate numbers (default crlf)
 110:     -equal_width bool - equalize width by padding with leading zeros.
 111:     -first value      - Sequence is started with this value.
 112:     -last value       - Sequence is ended with this value.
 113:     -incremrent value - Sequence is incremented/decremented by this value.
 114: "@;
 115: }
 116: else
 117: {
 118:   Do-Seq -filespec $filespec -separator $separator -equal_width $equal_width `
 119:     -first $first -last $last -increment $increment;
 120: }

You can download the full script here: Seq.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
SYS-CON Events announced today that Ryobi Systems 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. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterprise adopting a hybrid or public cloud needs systems and tools that provide: Agility: ability to deliver applications and services faster, even in complex hybrid environments Easier manageability: enable reliable connectivity with complete oversight as the data center network evolves Greater efficiency: eliminate wasted effort while reducing errors and optimize asset utilization Security: imple...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
The next XaaS is CICDaaS. Why? Because CICD saves developers a huge amount of time. CD is an especially great option for projects that require multiple and frequent contributions to be integrated. But… securing CICD best practices is an emerging, essential, yet little understood practice for DevOps teams and their Cloud Service Providers. The only way to get CICD to work in a highly secure environment takes collaboration, patience and persistence. Building CICD in the cloud requires rigorous ar...
Transforming cloud-based data into a reportable format can be a very expensive, time-intensive and complex operation. As a SaaS platform with more than 30 million global users, Cornerstone OnDemand’s challenge was to create a scalable solution that would improve the time it took customers to access their user data. Our Real-Time Data Warehouse (RTDW) process vastly reduced data time-to-availability from 24 hours to just 10 minutes. In his session at 21st Cloud Expo, Mark Goldin, Chief Technolo...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that CAST Software will exhibit 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. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese 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. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
When it comes to cloud computing, the ability to turn massive amounts of compute cores on and off on demand sounds attractive to IT staff, who need to manage peaks and valleys in user activity. With cloud bursting, the majority of the data can stay on premises while tapping into compute from public cloud providers, reducing risk and minimizing need to move large files. In his session at 18th Cloud Expo, Scott Jeschonek, Director of Product Management at Avere Systems, discussed the IT and busine...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
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, will answer these questions and demonstrate techniques for implementing advanced scheduling. For example, using spot instances ...
First generation hyperconverged solutions have taken the data center by storm, rapidly proliferating in pockets everywhere to provide further consolidation of floor space and workloads. These first generation solutions are not without challenges, however. In his session at 21st Cloud Expo, Wes Talbert, a Principal Architect and results-driven enterprise sales leader at NetApp, will discuss how the HCI solution of tomorrow will integrate with the public cloud to deliver a quality hybrid cloud e...
SYS-CON Events announced today that Yuasa System 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. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
Companies are harnessing data in ways we once associated with science fiction. Analysts have access to a plethora of visualization and reporting tools, but considering the vast amount of data businesses collect and limitations of CPUs, end users are forced to design their structures and systems with limitations. Until now. As the cloud toolkit to analyze data has evolved, GPUs have stepped in to massively parallel SQL, visualization and machine learning.
DevOps is under attack because developers don’t want to mess with infrastructure. They will happily own their code into production, but want to use platforms instead of raw automation. That’s changing the landscape that we understand as DevOps with both architecture concepts (CloudNative) and process redefinition (SRE). Rob Hirschfeld’s recent work in Kubernetes operations has led to the conclusion that containers and related platforms have changed the way we should be thinking about DevOps and...