Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 874
Mark Kadlec Avatar asked Mar 15 '12 18:03

Mark Kadlec


People also ask

How do I go to parent directory in Shell?

You can go back to the parent directory of any current directory by using the command cd .. , as the full path of the current working directory is understood by Bash . You can also go back to your home directory (e.g. /users/jpalomino ) at any time using the command cd ~ (the character known as the tilde).

How do I find the directory in PowerShell?

PowerShell Get Current Directory of Script File To get current directory of script file or running script, use $PSScriptRoot automatic variable. PSScriptRoot variable contains full script to path which invoke the current command.

How do I get to the root directory in PowerShell?

The Windows PowerShell prompt opens by default at the root of your user folder. Change to the root of C:\ by entering cd c:\ inside the Windows PowerShell prompt.


1 Answers

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.

like image 50
rerun Avatar answered Sep 18 '22 09:09

rerun