Home > Back-end >  How to get path of root directory?
How to get path of root directory?

Time:07-11

I have a powershell file called main.ps1 and it is in a project file structured as such:

APP > Tools > main.ps1

I'm wondering if there is a more efficient way to getting the path of the App directory. I'm using the following function:

$myFile = ($MyInvocation.MyCommand.Path)

function Root {
$parentPath = Split-Path -parent $myFile
$root = Split-Path -parent $parentPath
$base = Split-Path -parent $root
return $root, $base
}

$Root, $Base = Root

When the script is run MyInvocation saves the path of main.ps1 to the $myFile variable. Knowing this folder is always 2 folders deep in the App directory I use the -parent twice in a row and that gives me the path of the App folder.

Is there a more efficient way?

CodePudding user response:

You could cast [IO.FileInfo] from there you can get the parent directory of the file by calling the Directory property and lastly, this will return a IO.DirectoryInfo instance hence you can use the Parent property:

([IO.FileInfo] $MyInvocation.MyCommand.Path).Directory.Parent.FullName

There is also a more direct way of getting this information, using the automatic variable $PSScriptRoot:

Split-Path $PSScriptRoot

If you want to emulate what your function is doing for $base and $root you can do:

$root = ([IO.DirectoryInfo] $PSScriptRoot).Parent
$base = $root.Parent
$root.FullName
$base.FullName
  • Related