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

一曲冷凌霜 提交于 2019-12-23 12:24:19

问题


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

回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/52183213/get-great-grand-parent-folder-path-three-levels-up-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!