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)
.
Comments
-
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 calledData
with a fileTest.txt
, so I would like to seeData\Test.txt
instead ofC:\MyScript\Data\Test.txt
-
VinyJones almost 5 yearsis it possible to define another base directory than the current one ?
-
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 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/…