PowerShell: calculating a relative path

Sometimes you need a simple thing like calculating the relative path of a file given its full path and a base path. For example you have a file c:\a\b\c\d\e.doc and a base path c:\a\b\c, the relative path is now d\e.doc. I use the following PowerShell function to do this, actually using only .Net framework commands;-)

function global:RelativePath
{
    param
    (
        [string]$path = $(throw "Missing: path"),
        [string]$basepath = $(throw "Missing: base path")
    )
    
    return [system.io.path]::GetFullPath($path).SubString([system.io.path]::GetFullPath($basepath).Length + 1)
}    

Note that I use GetFullPath to get rid of things like .. in a path, like in c:\a\b..\c\d\e.

Published Friday, December 29, 2006 1:55 AM by svdoever
Filed under: ,

Comments

Saturday, January 13, 2007 3:33 PM by :-)

# re: PowerShell: calculating a relative path

you probably already discovered that this algorithm doesnt work with paths such as:

c:\program files\Microsoft Office\Templates (and)

c:\program files\My Program\bin

Wednesday, January 17, 2007 2:14 PM by Serge van den Oever [Macaw]

# re: PowerShell: calculating a relative path

I'm aware of that, it is assumed that base path is above the specified path, it does no .. path calculations!

Thursday, October 18, 2007 11:36 AM by Patrick Smacchia

# re: PowerShell: calculating a relative path

I just released an open-source library that helps handling complex path scenario such as relative/absolute conversion, rebasing, and much more

www.codeplex.com/FileDirectoryPath

Leave a Comment

(required) 
(required) 
(optional)
(required)