sourcecode

패키지에서 powershell ps1 스크립트를 실행하는 방법.json "jun"?

copyscript 2023. 9. 6. 22:14
반응형

패키지에서 powershell ps1 스크립트를 실행하는 방법.json "jun"?

PowerShell ps1 스크립트를 실행하려면 어떻게 해야 합니까?package.json"무서운"?

나는 기본적인 스크립트를 패키지로 설정하는 방법을 알고 있습니다.json "jun".예를 들어 다음 구성을 사용하여 실행할 수 있습니다.npm run test콘솔에 "이것은 테스트일 뿐입니다"라고 출력됩니다.

"scripts": {
  "test": "echo \"this is only a test\""
}

하지만 PowerShell 스크립트를 실행하는 좀 더 고급 시나리오가 있습니다.이와 같은 것:

"scripts": {
  "buildAngular": "buildAngular.ps1"
}

스크립트 객체를 통해 이와 같은 ps1 스크립트를 실행할 수 있습니까?특별한 설정/구성이 필요합니까?추가적인 제약 조건이 있습니까?

파워셸이 당신의 경로 안에 있다고 가정할 때, 당신은 이것을 이렇게 부를 수 있습니다.

"scripts": {
    "test": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./test.ps1"
}

Powershell v4가 탑재된 Windows 7에서 테스트되었습니다.

제한 사항은 Powershell을 설치하고 경로에 설치해야 한다는 것입니다.저는 리눅스용 파워셸로 테스트하지 않았기 때문에 이 솔루션이 다른 플랫폼에서 휴대할 수 있을지는 현재로서는 확신할 수 없습니다.

PowerShell 명령어 앞에 "powershell"을 붙입니다.

"command": "powershell Remove-Item ..\\folder\\file; Copy-Item -Path folder\\* -Destination ..\\other-folder -Recurse",
"buildAngular": "powershell buildAngular.ps1"

다음을 통해 스크립트-쉘 구성을 설정할 수 있습니다.npm config set script-shell "powershell"또는 환경 변수$env:npm_config_script_shell="powershell"

그러면 당신은 사용할 수 있습니다.

"scripts": {
    "test": "Write-Host 'this is only a test'"
}

아니면

"scripts": {
    "buildAngular": ".\\buildAngular.ps1"
}

-NoProfile과 같은 매개 변수를 제공할 수 있는지 잘 모르겠습니다.

개인적으로, 나는 A를 부르는 것을 선호합니다..bat대본과 합격.ps1인수로 실행할 파일 이름입니다.분명히 이것은 윈도우에서만 작동할 것입니다. 그래서 YMMV.

배치 스크립트 내에서 PowerShell Core의 존재 여부를 확인한 후 'Native' PowerShell로 되돌릴 수 있습니다.당신은 또한 당신의.-NoProfile -ExecutionPolicy배치 스크립트에서도 코드를 사용할 수 있기 때문에 좀 더 깔끔합니다.package.json파일.

패키지.json:

"scripts": {
  "test": "build-scripts\RunBuildScript.bat test"
}

빌드 스크립트를 실행합니다.배트:

@ECHO OFF

REM Check the argument passed in. You could also check if the file actually exists.
SET "NpmBuildScriptName=%1"
IF ["%NpmBuildScriptName%"] == [""] (
    ECHO "Could not find the name of the script."
    GOTO :TidyUp
)

REM Perform some checks for PowerShell Core in the file system.
FOR %%s IN ("PowerShell\pwsh.exe" "\PowerShellCore\pwsh.exe") DO (
    IF EXIST %%s (
        ECHO "PowerShell found at %%s"
        SET "PowerShellPath=%%s"
        GOTO :ExecuteScript
    )
)

REM If you can't find PowerShell, use the default.
IF ["%PowerShellPath%"] == [""] (
    ECHO "PowerShell Core was not found. Defaulting to native PowerShell"
    SET "PowerShellPath=powershell"
    GOTO :ExecuteScript
)

:ExecuteScript
    %PowerShellPath% -NoProfile -ExecutionPolicy Unrestricted -Command "%NpmBuildScriptName%.ps1"
    GOTO :TidyUp

:TidyUp
    REM Wipe after using.
    SET "NpmBuildScriptName="

ECHO 0

test.ps1

Write-Host "this is only a test"

분명히 텍스트를 출력하기 위해 뛰어내려야 할 많은 희망들이 있지만, 이 접근법은 그것을 좀 더 확장할 수 있게 만듭니다.

언급URL : https://stackoverflow.com/questions/46353836/how-to-execute-powershell-ps1-scripts-from-package-json-scripts

반응형