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.

basename

The Unix “basename” command will delete any prefix up to the last slash (‘/’) character and return the result. 

For my PowerShell implementation, I’ve switched the slash path separator character with the Windows backslash (‘\’) path separator. 

PowerShell does have the Split-Path cmdlet that will parse a path into it’s components.  And with it’s “-Leaf” argument, you can extract the basename equivalent.  My first implementation used this route, but the Split-Path cmdlet didn’t work correctly with relative paths.  More specifically, the Unix command passing in “.” would return “.”.  PowerShell returns the value of the current directory.   I tested out the “-LiteralPath” option but it still required a “-Path” option and would not interpret the “.” or “..” as literal strings.

So, I went ahead and wrote a little reverse string walking loop which turns out to be about 25% faster than using “Split-Path –Leaf”.  I’ve also included in this script a few unit tests I ran to verify the output.