How to get the parent parent directory in Powershell?

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

$scriptPath = (Get-ScriptDirectory); 

Now I would like to find a directory with two parent levels.

I need a good way:

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

Can I get rootPath in one line of code?

+49
scripting powershell
Mar 15 '12 at 18:03
source share
8 answers

Catalog Version

get-item is your friendly help here.

 (get-item $scriptPath ).parent.parent 

If you only want a string

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

File version

If $scriptPath points to a file, you must first call the Directory property, so the call will look like this:

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

Notes
This will only work if $scriptPath . Otherwise, you must use the Split-Path cmdlet.

+89
Mar 15 '12 at 18:13
source share

You can break it into a backslash and take the next-last with negative indexing of the array to get only the grandparent directory name.

 ($scriptpath -split '\\')[-2] 

You need to double the backslash to avoid it in regular expression.

To get all the way:

 ($path -split '\\')[0..(($path -split '\\').count -2)] -join '\' 

And, looking at the parameters for split-path, it takes the path as input for the pipeline, therefore:

 $rootpath = $scriptpath | split-path -parent | split-path -parent 
+14
Mar 15 '12 at 18:12
source share

I decided like this:

 $RootPath = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent 
+14
Dec 04 '15 at 13:48
source share

you can use

 (get-item $scriptPath).Directoryname 

to get the string path or if you want to use the directory type:

 (get-item $scriptPath).Directory 
+5
Sep 26 '13 at 14:37
source share

In PowerShell 3, $PsScriptRoot or for your question about two parents,

 $dir = ls "$PsScriptRoot\..\.." 
+3
Oct 08 '13 at 19:21
source share
 Split-Path -Path (Get-Location).Path -Parent 
+1
Dec 27 '17 at 7:11
source share

If you want to use $ PSScriptRoot, you can do

 Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve 
0
Apr 12 '17 at 9:54 on
source share

In powershell:

$ this_script_path = $ (Get-Item $ ($ MyInvocation.MyCommand.Path)). DirectoryName

$ parent_folder = Split-Path $ this_script_path -Leaf

-one
Nov 23 '15 at 11:59
source share



All Articles