program tip

Powershell에서 부모의 부모 디렉터리를 얻는 방법은 무엇입니까?

radiobox 2020. 10. 18. 09:15
반응형

Powershell에서 부모의 부모 디렉터리를 얻는 방법은 무엇입니까?


따라서 변수에 저장된 디렉토리가 있으면 다음과 같이 말하십시오.

$scriptPath = (Get-ScriptDirectory);

이제 부모 수준 의 디렉토리를 찾고 싶습니다 .

좋은 방법이 필요합니다.

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

한 줄의 코드로 rootPath에 액세스 할 수 있습니까?


디렉토리 버전

get-item 당신의 친절한 도움의 손길입니다.

(get-item $scriptPath ).parent.parent

문자열 만 원하는 경우

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

파일 버전

$scriptPath파일을 가리키는 경우 Directory먼저 속성 을 호출해야 하므로 호출은 다음과 같습니다.

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

주의
이것은 $scriptPath존재하는 경우에만 작동 합니다. 그렇지 않으면 Split-Pathcmdlet 을 사용해야 합니다.


다음과 같이 해결했습니다.

$RootPath = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent

백 슬래시에서 분할하고 음의 배열 인덱싱을 사용하여 마지막 순서를 가져와 조부모 디렉토리 이름 만 얻을 수 있습니다.

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

정규식에서 이스케이프하려면 백 슬래시를 두 배로 늘려야합니다.

전체 경로를 얻으려면 :

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

그리고 split-path의 매개 변수를 보면 경로를 파이프 라인 입력으로 사용하므로 다음과 같습니다.

$rootpath = $scriptpath | split-path -parent | split-path -parent

당신이 사용할 수있는

(get-item $scriptPath).Directoryname

문자열 경로를 가져 오거나 디렉토리 유형을 사용하려면 다음을 사용하십시오.

(get-item $scriptPath).Directory

PowerShell 3에서 $PsScriptRoot또는 두 부모에 대한 질문에 대해

$dir = ls "$PsScriptRoot\..\.."

split-path필요한만큼 간단히 연결할 수 있습니다 .

$rootPath = $scriptPath | split-path | split-path

Split-Path -Path (Get-Location).Path -Parent

$ PSScriptRoot를 사용하려면 할 수 있습니다.

Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve

powershell에서 :

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

$parent_folder = Split-Path $this_script_path -Leaf

참고 URL : https://stackoverflow.com/questions/9725521/how-to-get-the-parents-parent-directory-in-powershell

반응형