I'd like to convert a path to a relative path in a PowerShell script. How do I do this using PowerShell?
For example:
Path to convert: c:\documents\mynicefiles\afile.txt Reference path: c:\documents Result: mynicefiles\afile.txt
And
Path to convert: c:\documents\myproject1\afile.txt Reference path: c:\documents\myproject2 Result: ..\myproject1\afile.txt
The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.
-LiteralPath. Specifies the path to be resolved. The value of the LiteralPath parameter is used exactly as typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks ( ' ).
In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.
I found something built in, Resolve-Path:
Resolve-Path -Relative
This returns the path relative to the current location. A simple usage:
$root = "C:\Users\Dave\" $current = "C:\Users\Dave\Documents\" $tmp = Get-Location Set-Location $root Resolve-Path -relative $current Set-Location $tmp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With