简体   繁体   中英

how to execute powershell ps1 scripts from package.json “scripts”?

How can I execute PowerShell ps1 scripts from package.json "scripts"?

I know how to set up a basic script in package.json "scripts". For example with the following configuration, I can exec npm run test which will output "this is only a test" to the console:

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

However, I have a more advanced scenario where I'd like to execute a PowerShell script. Something like this:

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

Can I exec a ps1 script like this via the scripts object? Is any special setup/config required? Are there any additional constraints?

Assuming powershell is in you PATH you can call it like this:

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

Tested on Windows 7 with Powershell v4.

Limitations are that you need Powershell installed and in your PATH. I didn't test it with Powershell for Linux, so not sure if this solution will be portable to other platform for now.

You might set the script-shell config - either via npm config set script-shell "powershell" or environment variable $env:npm_config_script_shell="powershell"

Then you could use

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

or

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

I'm not sure whether you can supply parameters like -NoProfile though.

在 PowerShell 命令前加上“powershell”,例如,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM