Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get relative path of files in sub-folders from the current directory

Is there any straight-forward way (by use of cmdlets or .NET classes) to obtain only the relative path of a file in a sub-folder from a given path?

eg current folder is C:\MyScript and there is a sub-folder called Data with a file Test.txt, so I would like to see Data\Test.txt instead of C:\MyScript\Data\Test.txt

like image 579
blue18hutthutt Avatar asked Jun 10 '12 21:06

blue18hutthutt


People also ask

How do I find the relative path of a file in Python?

path. relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path.

How do I find the relative file path in Windows?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).


2 Answers

The Resolve-Path cmdlet has a -Relative parameter that will return a path relative to the current directory:

Set-Location C:\MyScript $relativePath = Get-Item Data\Test.txt | Resolve-Path -Relative 
like image 50
Aaron Jensen Avatar answered Oct 05 '22 17:10

Aaron Jensen


In case the directory doesn't exist, or the base directory should be different from the current working directory, there's a .NET method [IO.Path]::GetRelativePath(String from, String to).

like image 24
a-n Avatar answered Oct 05 '22 18:10

a-n