Search code examples
powershellpathscripting

How to get the Parent's parent directory in Powershell?


So if I have a directory stored in a variable, say:

$scriptPath = (Get-ScriptDirectory);

Now I would like to find the directory two parent levels up.

I need a nice way of doing:

$parentPath = Split-Path -parent $scriptPath
$rootPath = Split-Path -parent $parentPath

Can I get to the rootPath in one line of code?


Solution

  • Version for a directory

    get-item is your friendly helping hand here.

    (get-item $scriptPath ).parent.parent
    

    If you Want the string only

    (get-item $scriptPath ).parent.parent.FullName
    

    Version for a file

    If $scriptPath points to a file then you have to call Directory property on it first, so the call would look like this

    (get-item $scriptPath).Directory.Parent.Parent.FullName
    

    Remarks
    This will only work if $scriptPath exists. Otherwise you have to use Split-Path cmdlet.