71334

Getting relative path from absolute path in PowerShell

The problem

You have an absolute path, but you want it to be relative to another path.

Example:

P:/SO/data/database.txt --> Now we want the filename to be relative to: P:/SO/team/lists/ ../../data/database.txt

I have already found the Stack Overflow question How to convert absolute path to relative path in PowerShell?.

One answer links to an already developed Cmdlet, but this one didn't work for me. And the trick using Set/Get-Location requires the paths to exist.

Answer1:

The solution

I found an answer from Gordon written in PHP: Getting relative path from absolute path in PHP.

Here is my port to PowerShell:

<# This is probably not the best code I've ever written, but I think it should be readable for most (advanced) users. I will wrap this function into a Cmdlet when I have time to do it. Feel free to edit this answer and improve it! #> function getRelativePath([string]$from, [string]$to, [string]$joinSlash='/') { $from = $from -replace "(\\)", "/"; $to = $to -replace "(\\)", "/"; $fromArr = New-Object System.Collections.ArrayList; $fromArr.AddRange($from.Split("/")); $relPath = New-Object System.Collections.ArrayList; $relPath.AddRange($to.Split("/")); $toArr = New-Object System.Collections.ArrayList; $toArr.AddRange($to.Split("/")); for ($i=0; $i -lt $fromArr.Count; $i++) { $dir = $fromArr[$i]; # Find first non-matching directory if ($dir.Equals($toArr[$i])) { # ignore this directory $relPath.RemoveAt(0); } else { # Get number of remaining directories to $from $remaining = $fromArr.Count - $i; if ($remaining -gt 1) { # Add traversals up to first matching directory $padLength = ($relPath.Count + $remaining - 1); # Emulate array_pad() from PHP for (; $relPath.Count -ne ($padLength);) { $relPath.Insert(0, ".."); } break; } else { $relPath[0] = "./" + $relPath[0]; } } } return $relPath -Join $joinSlash; }

<strong>Attention:</strong> - You From path has to end with a slash!

Example

getRelativePath -From "P:/SO/team/lists/" -To "P:/SO/data/database.txt"; --> ../../data/database.txt getRelativePath -From "C:/Windows/System32/" -To "C:/Users/ComFreek/Desktop/SO.txt"; --> ../../Users/ComFreek/Desktop/SO.txt

Recommend

  • How to get the current queue name in swift 3
  • String Selection Sort in C++
  • How can I disable clear of clipboard on exit of PyQt application?
  • Replace a string with another string from a list depending on the value
  • Android: avoid calling onCreate() when back from another activity
  • Getting Facebook error 11
  • Middleman: referencing URL stored in a data file from markdown
  • Is it possible to specialize on a static lifetime?
  • ASP.NET MVC2 Error: No parameterless constructor defined for this object
  • How to make SASS put relative paths in its output
  • Quick Question About Get and Set
  • CORS with socket.io
  • redirect_to root_url and return unless @user.activated
  • JSR-330 support in Picocontainer : @Inject … @Named(\"xxx)
  • Prevent Tomcat from caching request during starup
  • Updating both a ConcurrentHashMap and an AtomicInteger safely
  • Zoom in and out of jPanel
  • Access Android Market through SSH tunnel
  • Firefox Extension - Monitor refresh and change of tab
  • Insert new calendar with SyncAdapter- Calendar API Android
  • Saving Changes After In-App Purchase Has Been Purchased
  • Sort List of Strings By Version
  • Ensure fsync did its job
  • How to run “Deployd” on port 80 instead of port 5000 in webserver.
  • Xcode 4 NSLog Macro link in Xcode 3
  • script to move all files from one location to another location
  • Upload files with Ajax and Jquery
  • Adding custom controls to a full screen movie
  • To display the title for the current loaction in map in iphone
  • Do I've to free mysql result after storing it?
  • A cron job substitute?
  • json Serialization in asp
  • How to set the response of a form post action to a iframe source?
  • Change div Background jquery
  • File not found error Google Drive API
  • Qt: Run a script BEFORE make
  • Django query for large number of relationships
  • reshape alternating columns in less time and using less memory
  • How can i traverse a binary tree from right to left in java?
  • How do I use LINQ to get all the Items that have a particular SubItem?