Home > Enterprise >  What to append to a path to make it point to the file system root?
What to append to a path to make it point to the file system root?

Time:03-16

I have some path, let's say C:\Windows\System32\WindowsPowerShell\. I would like to find such a string, that when appended (from the right side), will make this path point to C:\.

Well, that is easy if the path is set; I could just make it C:\Windows\System32\WindowsPowerShell\..\..\..\.

What I am looking for however, is a fixed string that would work every time, no matter how the initial path looks (and especially how long it is). Does Windows offer some tricks to help this? If it is impossible to achieve, then it's a valid answer.

Bonus points: can I refer to a different hard drive this way?

CodePudding user response:

Use Convert-Path to resolve/consolidate the given path, then keep adding .. until you reach the root of the volume:

# Grab current location from `$pwd` automatic variable
$path = "$pwd"

# Calculate path root 
$root = [System.IO.Path]::GetPathRoot($path)

while((Convert-Path $path) -ne $root){
  # We haven't reached the root yet, keep backing up
  $path = Join-Path $path '..'
}

$path now contains C:\Current\Relative\Path\..\..\.. and you can now do:

& path\to\myBinary.exe (Join-Path $path.Replace("$pwd","").TrimStart('\') targetfile.ext)

$path.Replace("$pwd", "") gives us just \..\..\.., and TrimStart('\') removes the leading path separator so as to make the path relative, so the resulting string passed to the binary will be ..\..\..\targetfile.ext

  • Related