SYS-CON MEDIA Authors: Pat Romanski, Liz McMillan, Yeshim Deniz, Elizabeth White, Courtney Abud

Blog Feed Post

Unix To PowerShell - Dirname

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.

dirname

The Unix “dirname” command will strip any non-directory suffix from a file name.  Given a NAME, dirname will print the name with it’s trailing “/” component removed.  If NAME contains no “/” characters, it will output “.” (meaning the current directory).

Since PowerShell is run on windows, my script will substitute the forward slash with the windows backslash directory specifier.  This can be overridden by changing the $script:SEPARATOR variable in the script.

At first I thought that a simple [System.IO.FileInfo] cast would do the trick, but it doesn’t behave the same if you give a non-fully qualified directory (ie foo.txt, .\foo.txt, ..\foo.txt).  For non-qualified paths, the FileInfo class will default to the $env:home directory (ie. C:\Users\Joe) which is not the behavior of the Unix dirname command.  I also looked at using the builtin Get-ChildItem cmdlet but that will not work for paths that are not present on the file system and this command should work for any string passed in.

I’ve included a few unit test cases with the Do-DirNameUnitTests function to show the inputs and expected outputs.

The script takes only one argument, the name to process and returns the dirname to the output.

   1: #----------------------------------------------------------------
   2: # Dirname.ps1
   3: #----------------------------------------------------------------
   4: param
   5: (
   6:   [string]$name = $null
   7: );
   8:  
   9: $script:SEPARATOR = "\";
  10:  
  11: #----------------------------------------------------------------
  12: # function Do-Dirname
  13: #----------------------------------------------------------------
  14: function Do-Dirname()
  15: {
  16:   param
  17:   (
  18:     [string]$name = $null
  19:   );
  20:   
  21:   $dirname = ".";
  22:   
  23:   if ( $name  )
  24:   {
  25:     if ( $name -ne $script:SEPARATOR )
  26:     {
  27:       $start_index = $name.Length-1;
  28:       
  29:       # for paths like \foo\bar\, bypass the trailing separator
  30:       if ( ($name.Length -gt 1) -and $name.EndsWith($script:SEPARATOR) )
  31:       {
  32:         $start_index--;
  33:       }
  34:       
  35:       # Reverse Iterate through the string until we find a path separator
  36:       for($dirlen=$start_index; $dirlen -ge 0; $dirlen--)
  37:       {
  38:         if ( $name[$dirlen] -eq $script:SEPARATOR )
  39:         {
  40:           break;
  41:         }
  42:       }
  43:       if ( $dirlen -eq -1 )
  44:       {
  45:         # No path separators found, default to the current directory
  46:         $dirname = "."
  47:       }
  48:       else
  49:       {
  50:         $dirname = $name.Substring(0, $dirlen);
  51:         
  52:         #sanity checks
  53:         if ( $dirname.Length -eq 0 ) { $dirname = $script:SEPARATOR; }
  54:         if ( $dirname -like "[a-zA-Z]:" ) { $dirname += $script:SEPARATOR; }
  55:       }
  56:     }
  57:   }
  58:   $dirname;
  59: }
  60:  
  61: #----------------------------------------------------------------
  62: # function Do-DirnameUnitTests
  63: #----------------------------------------------------------------
  64: function Do-DirnameUnitTests()
  65: {
  66:   $tests = @( 
  67:     @("foo", "."),
  68:     @("foo\", "."),
  69:     @("", "."),
  70:     @("\foo", "\"),
  71:     @("\foo\", "\"),
  72:     @("\foo\bar", "\foo"),
  73:     @("\foo\bar\", "\foo"),
  74:     @("c:\foo", "c:\"),
  75:     @("c:\foo\bar", "c:\foo"),
  76:     @("c:\foo\bar\", "c:\foo")
  77:   );
  78:   
  79:   $success = "PASS";
  80:   
  81:   "  {0,-15}      {1,-15}       {2,-15}    {3}" -f ("Test", "Expected", "Found", "Pass");
  82:   foreach ($test in $tests)
  83:   {
  84:     $result = Do-Dirname $test[0];
  85:     $status = $result -eq $test[1];
  86:     "(""{0,-15}"" -> ""{1,-15}"") -> ""{2,-15}"" : {3}" -f ($test[0], $test[1], $result, $status);
  87:     #Write-Host "TEST: (""$($test[0])"" -> ""$($test[1])"") -> ""$result"" : $status";
  88:     if ( ! $status ) { $success = "FAIL"; }
  89:   }
  90:   ""
  91:   "RESULT: $success";
  92:  
  93: }
  94:  
  95: Do-Dirname -name $name;

You can get the full script here: Dirname.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
Platform9, the open-source-as-a-service company making cloud infrastructure easy, today announced the general availability of its Managed Kubernetes service, the industry's first infrastructure-agnostic, SaaS-managed offering. Unlike legacy software distribution models, Managed Kubernetes is deployed and managed entirely as a SaaS solution, across on-premises and public cloud infrastructure. The company also introduced Fission, a new, open source, serverless framework built on Kubernetes. These ...
Serverless Computing or Functions as a Service (FaaS) is gaining momentum. Amazon is fueling the innovation by expanding Lambda to edge devices and content distribution network. IBM, Microsoft, and Google have their own FaaS offerings in the public cloud. There are over half-a-dozen open source serverless projects that are getting the attention of developers.
As Apache Kafka has become increasingly ubiquitous in enterprise environments, it has become the defacto backbone of real-time data infrastructures. But as streaming clusters grow, integrating with various internal and external data sources has become increasingly challenging. Inspection, routing, aggregation, data capture, and management have all become time-consuming, expensive, poorly performing, or all of the above. Elements erases this burden by allowing customers to easily deploy fully man...
IT professionals are also embracing the reality of Serverless architectures, which are critical to developing and operating real-time applications and services. Serverless is particularly important as enterprises of all sizes develop and deploy Internet of Things (IoT) initiatives. Serverless and Kubernetes are great examples of continuous, rapid pace of change in enterprise IT. They also raise a number of critical issues and questions about employee training, development processes, and opera...
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 produce software that is obsolete at launch. DevOps may be disruptive, but it is essential. DevOpsSUMMIT at CloudEXPO expands the DevOps community, enable a wide sharing of knowledge, and educate delegates and technology providers alike.
As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility.
This month @nodexl announced that ServerlessSUMMIT & DevOpsSUMMIT own the world's top three most influential Kubernetes domains which are more influential than LinkedIn, Twitter, YouTube, Medium, Infoworld and Microsoft combined. NodeXL is a template for Microsoft® Excel® (2007, 2010, 2013 and 2016) on Windows (XP, Vista, 7, 8, 10) that lets you enter a network edge list into a workbook, click a button, see a network graph, and get a detailed summary report, all in the familiar environment of...
Technology has changed tremendously in the last 20 years. From onion architectures to APIs to microservices to cloud and containers, the technology artifacts shipped by teams has changed. And that's not all - roles have changed too. Functional silos have been replaced by cross-functional teams, the skill sets people need to have has been redefined and the tools and approaches for how software is developed and delivered has transformed. When we move from highly defined rigid roles and systems to ...
The Kubernetes vision is to democratize the building of distributed systems. As adoption of Kubernetes increases, the project is growing in popularity; it currently has more than 1,500 contributors who have made 62,000+ commits. Kubernetes acts as a cloud orchestration layer, reducing barriers to cloud adoption and eliminating vendor lock-in for enterprises wanting to use cloud service providers. Organizations can develop and run applications on any public cloud, such as Amazon Web Services, Mic...
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 ...
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...
Implementation of Container Storage Interface (CSI) for Kubernetes delivers persistent storage for compute running in Kubernetes-managed containers. This future-proofs Kubernetes+Storage deployments. Unlike the Kubernetes Flexvol-based volume plugin, storage is no longer tightly coupled or dependent on Kubernetes releases. This creates greater stability because the storage interface is decoupled entirely from critical Kubernetes components allowing separation of privileges as CSI components do n...
With container technologies widely recognized as the cloud-era standard for workload scaling and application mobility, organizations are increasingly seeking to support container-based workflows. In particular, the desire to containerize a diverse spectrum of enterprise applications has highlighted the need for reliable, container-friendly, persistent storage. However, to effectively complement today's cloud-centric container orchestration platforms, persistent storage solutions must blend relia...
Applications with high availability requirements must be deployed to multiple clusters to ensure reliability. Historically, this has been done by pulling nodes from other availability zones into the same cluster. However, if the cluster failed, the application would still become unavailable. Rancher’s support for multi-cluster applications is a significant step forward, solving this problem by allowing users to select the application and the target clusters, providing cluster specific data. Ranc...
AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.