Development Tip

PowerShell 스크립트의 파일 시스템 위치를 어떻게 얻을 수 있습니까?

yourdevel 2020. 12. 3. 20:41
반응형

PowerShell 스크립트의 파일 시스템 위치를 어떻게 얻을 수 있습니까?


에있는 PowerShell 스크립트가 있습니다 D:\temp.

이 스크립트를 실행할 때 파일의 현재 위치가 나열되기를 원합니다. 어떻게해야합니까?

예를 들어,이 코드는 DOS 배치 파일에서이를 수행합니다. 이것을 PowerShell 스크립트로 변환하려고합니다 ...

FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa
CD /d "%this_cmds_dir%"

PowerShell 3 이상

실행중인 스크립트의 경로는 다음과 같습니다.

$PSCommandPath

디렉토리는 다음과 같습니다.

$PSScriptRoot

파워 셸 2

실행중인 스크립트의 경로는 다음과 같습니다.

$MyInvocation.MyCommand.Path

디렉토리는 다음과 같습니다.

$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent

Roman Kuzmin이 imho라는 질문에 대답했습니다. 모듈을 가져 오면 (을 통해 Import-Module) $PsScriptRoot모듈 내부의 자동 변수에 액세스 할 수 있다는 점을 추가하겠습니다. 그러면 모듈 위치를 알려줍니다.


그만한 가치는 스크립트 및 PowerShell ISE의 ​​PowerShell V5에서 저에게 효과적이라는 것을 알았습니다.

try {
    $scriptPath = $PSScriptRoot
    if (!$scriptPath)
    {
        if ($psISE)
        {
            $scriptPath = Split-Path -Parent -Path $psISE.CurrentFile.FullPath
        } else {
            Write-Host -ForegroundColor Red "Cannot resolve script file's path"
            exit 1
        }
    }
} catch {
    Write-Host -ForegroundColor Red "Caught Exception: $($Error[0].Exception.Message)"
    exit 2
}

Write-Host "Path: $scriptPath"

HTH

PS 전체 오류 처리가 포함되었습니다. 그에 따라 필요에 맞게 조정하십시오.

참고 URL : https://stackoverflow.com/questions/3667238/how-can-i-get-the-file-system-location-of-a-powershell-script

반응형