programing

상대 경로가 있는 다른 PowerShell 스크립트를 호출하려면 어떻게 해야 합니까?

minimums 2023. 11. 4. 10:31
반응형

상대 경로가 있는 다른 PowerShell 스크립트를 호출하려면 어떻게 해야 합니까?

다음 디렉토리 트리가 있습니다.

e:\powershell\services\This-Script-Here-Should-Call-Press any key to continue.ps1
e:\powershell\utils\Press any key to continue.ps1

이제 "services" 폴더에 있는 스크립트에서 "Press any key to continue.ps1" 이라는 이름의 스크립트를 호출합니다.그걸 어떻게 하는 거죠?나는 상대적인 경로를 알 수가 없습니다.

저는 이런 식으로 하려고 했습니다.

"$ '.\..\utils\Press any key to continue.ps1'"

하지만 효과가 없었습니다.

작업 내용에 따라 다음과 같은 작업을 수행할 수 있습니다.

& "..\utils\Press any key to continue.ps1"

아니면

. "..\utils\Press any key to continue.ps1"

(와 사용의 차이를 lookup하고 어떤 것을 사용할지 결정)

이것이 제가 이러한 상황에 대처하는 방법입니다(그리고 @Shay가 언급한 것과 약간의 차이가 있음).

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$utilsDir  = Join-Path -Path $scriptDir -ChildPath ..\utils

& "$utilsDir\Press any key to continue.ps1"

호출 스크립트에 다음 함수를 넣어 디렉토리 경로를 가져오고 스크립트 이름과 함께 utils 경로에 가입합니다.

# create this function in the calling script
function Get-ScriptDirectory { Split-Path $MyInvocation.ScriptName }

# generate the path to the script in the utils directory:
$script = Join-Path (Get-ScriptDirectory) 'utils\Press any key to continue.ps1'

# execute the script
& $script 

현재 스크립트 경로 $PSScriptRoot 변수를 가져오려면 사용할 수 있습니다.예를 들어 다음은 solution\mainscript.ps1 solution\secondscript folder\secondscript.ps1 구조입니다.

#mainscript.ps1

$Second = Join-Path $PSScriptRoot '\secondscriptfolder\secondscript.ps1'

$Second

유익한 정보를 주셔서 감사합니다.저도 비슷한 문제가 있었는데, 부모 폴더에서 다른 스크립트를 호출하는 작업을 이렇게 할 수 있었습니다.

$CommandPath = (Get-Location).Path | Split-Path -Parent; $script = "$CommandPath\Logins\Login_SSI_SST_exch2010_DKSUND_Exchange365.ps1"; & $script

언급URL : https://stackoverflow.com/questions/7377981/how-do-i-call-another-powershell-script-with-a-relative-path

반응형