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.

1 Comment

  • 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

Comments have been disabled for this content.