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.