SYS-CON MEDIA Authors: Yeshim Deniz, Pat Romanski, Elizabeth White, Liz McMillan, William Schmarzo

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.


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: );
   9: $script:SEPARATOR = "\";
  11: #----------------------------------------------------------------
  12: # function Do-Dirname
  13: #----------------------------------------------------------------
  14: function Do-Dirname()
  15: {
  16:   param
  17:   (
  18:     [string]$name = $null
  19:   );
  21:   $dirname = ".";
  23:   if ( $name  )
  24:   {
  25:     if ( $name -ne $script:SEPARATOR )
  26:     {
  27:       $start_index = $name.Length-1;
  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:       }
  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);
  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: }
  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:   );
  79:   $success = "PASS";
  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";
  93: }
  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
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. 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 throughout enterprises of all sizes. We are offering early bird savings...
SUSE is a German-based, multinational, open-source software company that develops and sells Linux products to business customers. Founded in 1992, it was the first company to market Linux for the enterprise. Founded in 1992, SUSE is the world’s first provider of an Enterprise Linux distribution. Today, thousands of businesses worldwide rely on SUSE for their mission-critical computing and IT management needs.
The dream is universal: heuristic driven, global business operations without interruption so that nobody has to wake up at 4am to solve a problem. Building upon Nutanix Acropolis software defined storage, virtualization, and networking platform, Mark will demonstrate business lifecycle automation with freedom of choice and consumption models. Hybrid cloud applications and operations are controllable by the Nutanix Prism control plane with Calm automation, which can weave together the following: ...
Crosscode Panoptics Automated Enterprise Architecture Software. Application Discovery and Dependency Mapping. Automatically generate a powerful enterprise-wide map of your organization's IT assets down to the code level. Enterprise Impact Assessment. Automatically analyze the impact, to every asset in the enterprise down to the code level. Automated IT Governance Software. Create rules and alerts based on code level insights, including security issues, to automate governance. Enterpr...
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are repetitive and dull. Utilizing automation can improve your work life, automating away the drudgery and embracing the passion for technology that got you started in the first place. In this presentation, I'll talk about what automation is, and how to approach implementing it in the context of IT Operations. Ned will discuss keys to success in the long term and include practical real-world examples. Ge...
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.
Eric Taylor, a former hacker, reveals what he's learned about cybersecurity. Taylor's life as a hacker began when he was just 12 years old and playing video games at home. Russian hackers are notorious for their hacking skills, but one American says he hacked a Russian cyber gang at just 15 years old. The government eventually caught up with Taylor and he pleaded guilty to posting the personal information on the internet, among other charges. Eric Taylor, who went by the nickname Cosmo...
DevOpsSUMMIT at CloudEXPO, to be held June 25-26, 2019 at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Am...
The benefits of automated cloud deployments for speed, reliability and security are undeniable. The cornerstone of this approach, immutable deployment, promotes the idea of continuously rolling safe, stable images instead of trying to keep up with managing a fixed pool of virtual or physical machines. In this talk, we'll explore the immutable infrastructure pattern and how to use continuous deployment and continuous integration (CI/CD) process to build and manage server images for any platfo...
Automation is turning manual or repetitive IT tasks into a thing of the past-including in the datacenter. Nutanix not only provides a world-class user interface, but also a comprehensive set of APIs to allow the automation of provisioning, data collection, and other tasks. In this session, you'll explore Nutanix APIs-from provisioning to other Day 0, Day 1 operations. Come learn about how you can easily leverage Nutanix APIs for orchestration and automation of infrastructure, VMs, networking, an...
It cannot be overseen or regulated by any one administrator, like a government or bank. Currently, there is no government regulation on them which also means there is no government safeguards over them. Although many are looking at Bitcoin to put money into, it would be wise to proceed with caution. Regular central banks are watching it and deciding whether or not to make them illegal (Criminalize them) and therefore make them worthless and eliminate them as competition. ICOs (Initial Coin Offer...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Organize your corporate travel faster, at lower cost. Hotailors is a next-gen AI-powered travel platform. What is Hotailors? Hotailors is a platform for organising business travels that grants access to the best real-time offers from 2.000.000+ hotels and 700+ airlines in the whole world. Thanks to our solution you can plan, book & expense business trips in less than 5 minutes. Accordingly to your travel policy, budget limits and cashless for your employees. With our reporting, int...
The current environment of Continuous Disruption requires companies to transform how they work and how they engineer their products. Transformations are notoriously hard to execute, yet many companies have succeeded. What can we learn from them? Can we produce a blueprint for a transformation? This presentation will cover several distinct approaches that companies take to achieve transformation. Each approach utilizes different levers and comes with its own advantages, tradeoffs, costs, risks, a...