henrycarteruk
henrycarteruk

Reputation: 13217

Get great grand parent folder path (three levels up) in PowerShell?

Is there an elegant way to get the (great-grandparent folder) three levels up from a folder path?

I'm only looking to get C:\folderA\folderB from the full path, but both solutions just seem ugly to me.

$path = "C:\folderA\folderB\folderC\FolderD\folderE"

# option 1
(Get-Item $path).parent.parent.parent.FullName

# option 2    
$path | Split-Path -Parent | Split-Path -Parent | Split-Path -Parent

Upvotes: 5

Views: 1724

Answers (2)

gvee
gvee

Reputation: 17161

I guess you could use a wrapper function... not exactly ideal but a little fun:

function Split-PathLots {
    [CmdletBinding()]

    Param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Path
        ,
        [int]
        $NumberOfTimes = 1
    )

    Process {
        $PathToReturn = $Path
        Write-Verbose "Input = $Path"

        [int]$i = 1
        while ($i -le $NumberOfTimes) {
            $PathToReturn = $PathToReturn | Split-Path -Parent
            Write-Verbose "($i/$NumberOfTimes) $PathToReturn"
            $i++
        }

        return $PathToReturn
    }
}

$path = "C:\folderA\folderB\folderC\FolderD\folderE"

Write-Output (Split-PathLots -Path $path -NumberOfTimes 3 -Verbose)

output

VERBOSE: Input = C:\folderA\folderB\folderC\FolderD\folderE
VERBOSE: (1/3) C:\folderA\folderB\folderC\FolderD
VERBOSE: (2/3) C:\folderA\folderB\folderC
VERBOSE: (3/3) C:\folderA\folderB
C:\folderA\folderB

Upvotes: 2

marsze
marsze

Reputation: 17035

Try this (works only if the path exists):

(Get-Item "$path\..\..\..").FullName

Alternatively, if the path does not exist:

[System.IO.Path]::GetFullPath("$path\..\..\..")

You could also use this generic option for n levels:

[System.IO.Path]::GetFullPath($path + "\.." * $n)

Upvotes: 4

Related Questions