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

PowershellPowershell 2.0Powershell Ise

Powershell Problem Overview


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

Powershell Solutions


Solution 1 - Powershell

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 - Powershell

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionblue18hutthuttView Question on Stackoverflow
Solution 1 - PowershellAaron JensenView Answer on Stackoverflow
Solution 2 - Powershella-nView Answer on Stackoverflow