programing

명령줄에서 특정 PowerShell 함수 호출

copyandpastes 2023. 9. 3. 17:30
반응형

명령줄에서 특정 PowerShell 함수 호출

몇 가지 기능이 포함된 PowerShell 스크립트가 있습니다.명령줄에서 특정 함수를 호출하려면 어떻게 해야 합니까?

이것은 작동하지 않습니다.

powershell -File script.ps1 -Command My-Func

일반적으로 스크립트를 범위(글로벌, 스크립트 블록 내의 다른 스크립트)에 "도트"합니다.스크립트를 점으로 표시하면 중첩된 새 범위를 만들지 않고 해당 범위 내에서 스크립트를 로드하고 실행할 수 있습니다.기능을 사용하면 스크립트가 실행된 후에도 기능이 유지된다는 이점이 있습니다.스크립트를 도트해야 한다는 점을 제외하고는 Tomer가 제안하는 것을 수행할 수 있습니다. 예:

powershell -command "& { . <path>\script1.ps1; My-Func }"

현재 PowerShell 세션에서 이 기능을 실행하려면 다음을 수행합니다.

. .\script.ps1
My-Func

함수에 없는 스크립트는 실행되고 스크립트 변수는 글로벌 변수가 됩니다.

이 솔루션은 PowerShell 코어와 함께 작동합니다.

powershell -command "& { . .\validate.ps1; Validate-Parameters }" 

아래에 오류 메시지가 표시됩니다.Keith Hill이 제안한 대로 메모리에 로드하려면 파일 이름 앞에 점이 필요합니다.

MyFunction: The term 'MyFunction' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

아마도 비슷한 것.

powershell -command "& { script1.ps; My-Func }"

파일이 .ps1이 아닌 .ps1 파일인 경우 다음을 호출합니다.

powershell -command "& { Import-Module <path>\script1.psm1; My-Func }"

언급URL : https://stackoverflow.com/questions/1405750/calling-a-specific-powershell-function-from-the-command-line

반응형