Monday, February 02, 2009

PowerShell Snippet for Combining Directory Paths

System.IO.Path.Combine rocks for safely combining directory paths, but it’s got a silly inflexibility built in which means you’ve got to clean up paths you first pass in to it.

For example:

Path.Combine(“C:\Foo\”,  “\bar”) results in “\bar” because you’ve given Combine “\bar” which is a root-level folder. Unfortunately, there’s no flexible way in the API to deal with this, so you’ve got to do some pre-processing first.

My particular use case right now is that I don’t want any trailing slashes dealt with on the root (left) param, and I don’t care about starting slashes on the subdir (right), so I’m just going to get rid of both those. Ergo:

[char[]]$trimChars = '\\'
function FixTerminatingSlash ($root) {
    return $root.TrimEnd($trimChars)   

function FixStartingSlash($suffix) {
    return $suffix.TrimStart($trimChars)

function CombinePaths ([string]$root, [string]$subdir) {
    $left = FixTerminatingSlash($root)
    $right = FixStartingSlash($subdir)
    $fullPath = [System.IO.Path]::Combine($left, $right)
    return $fullPath


Invoke this via “CombinePaths <rootDir> <subDir>” with a space, not a comma, between the two. It’s not rocket science, and I’m sure some PowerShell guru will tell me all this can be done some other way in three characters – which is fine, so show me!


Peter Seale said...

Join-Path "C:\root\" "\subdirectory"

And yes, I went 2 years ignorant of Join-Path (and similarly using a lot of []::Combine()), so you're in good company.

Jim Holmes said...

Argh! Thanks for the tip, Peter!

Sure enough, it's right in Windows PowerShell Cookbook, too. I need to get more familiar with my copy of that!

Thanks, Jim.

Steve said...

And while you are talking about join-path, don't forget about the other path manipulation cmdlets - Split-Path, Resolve-Path, and Test-Path.

Subscribe (RSS)

The Leadership Journey