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

2

79

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

Unroot answered 10/6, 2012 at 21:45 Comment(2)
I guess this what you want - https://mcmap.net/q/181048/-how-to-normalize-a-path-in-powershellAdministrate
Related: https://mcmap.net/q/263083/-how-to-recurse-through-folders-and-display-relative-folder-path/7571258Sachasachem
W
140

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
Willardwillcox answered 11/6, 2012 at 5:7 Comment(4)
is it possible to define another base directory than the current one ?Farcy
@Farcy I haven't found a way but I used Push-Location and Pop-Location as a workaround to temporarily set the current directory to the other base directory in order to get the path relative to that directory. Kind of clunky but it works for me.Much
@Farcy Yes, if using .net core/.net standard you can use the .net method for this: [System.IO.Path]::GetRelativePath('c:\temp', 'c:\windows'). learn.microsoft.com/en-us/dotnet/api/…. For .net framework you'd need to roll your own: see #276189Fitter
@Farcy They finally added a RelativeBasePath option in Powershell 7.4.0 so you don't need to use .NET anymore: Resolve-Path -Path "C:\Temp" -RelativeBasePath "C:\Windows"Athirst
S
5

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).

Sosna answered 13/4, 2021 at 23:48 Comment(1)
Only available in .Net coreMenarche

© 2022 - 2025 — McMap. All rights reserved.