Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get path of root directory?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading