Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert absolute path to relative path in PowerShell?

Tags:

powershell

I'd like to convert a path to a relative path in a PowerShell script. How do I do this using PowerShell?

For example:

Path to convert: c:\documents\mynicefiles\afile.txt Reference path:  c:\documents Result:          mynicefiles\afile.txt 

And

Path to convert: c:\documents\myproject1\afile.txt Reference path:  c:\documents\myproject2 Result:          ..\myproject1\afile.txt 
like image 260
Dave Hillier Avatar asked Sep 12 '12 20:09

Dave Hillier


People also ask

How do you convert an absolute path to a relative path?

The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.

What is LiteralPath in PowerShell?

-LiteralPath. Specifies the path to be resolved. The value of the LiteralPath parameter is used exactly as typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks ( ' ).

Can an absolute path be a relative path?

In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.


1 Answers

I found something built in, Resolve-Path:

Resolve-Path -Relative 

This returns the path relative to the current location. A simple usage:

$root = "C:\Users\Dave\" $current = "C:\Users\Dave\Documents\" $tmp = Get-Location Set-Location $root Resolve-Path -relative $current Set-Location $tmp 
like image 122
Dave Hillier Avatar answered Sep 21 '22 09:09

Dave Hillier