76

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

androschuk.a
  • 289
  • 10
  • 22
blue18hutthutt
  • 3,191
  • 5
  • 34
  • 57

2 Answers2

131

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
Aaron Jensen
  • 25,861
  • 15
  • 82
  • 91
  • 3
    is it possible to define another base directory than the current one ? – VinyJones Jun 05 '19 at 14:20
  • 7
    @VinyJones 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. – Joe Savage Jul 29 '19 at 19:30
  • 3
    @VinyJones Yes, if using .net core/.net standard you can use the .net method for this: `[System.IO.Path]::GetRelativePath('c:\temp', 'c:\windows')`. https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrelativepath?view=net-6.0&viewFallbackFrom=netframework-2.0. For .net framework you'd need to roll your own: see https://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path – JohnLBevan Feb 15 '22 at 16:39
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).

a-n
  • 67
  • 1
  • 2