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

58,170

Solution 1

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

Solution 2

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

Share:
58,170
blue18hutthutt
Author by

blue18hutthutt

Just your average .NET developer

Updated on July 05, 2022

Comments

  • blue18hutthutt
    blue18hutthutt almost 2 years

    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

  • VinyJones
    VinyJones almost 5 years
    is it possible to define another base directory than the current one ?
  • Joe Savage
    Joe Savage almost 5 years
    @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.
  • JohnLBevan
    JohnLBevan about 2 years
    @VinyJones Yes, if using .net core/.net standard you can use the .net method for this: [System.IO.Path]::GetRelativePath('c:\temp', 'c:\windows'). docs.microsoft.com/en-us/dotnet/api/…. For .net framework you'd need to roll your own: see stackoverflow.com/questions/275689/…