简体   繁体   English

如何从 package.json “scripts” 执行 powershell ps1 脚本?

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

How can I execute PowerShell ps1 scripts from package.json "scripts"?如何从package.json “脚本”执行 PowerShell ps1 脚本?

I know how to set up a basic script in package.json "scripts".我知道如何在 package.json“脚本”中设置一个基本脚本。 For example with the following configuration, I can exec npm run test which will output "this is only a test" to the console:例如,使用以下配置,我可以 exec npm run test将输出“这只是一个测试”到控制台:

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

However, I have a more advanced scenario where I'd like to execute a PowerShell script.但是,我有一个更高级的场景,我想在其中执行 PowerShell 脚本。 Something like this:像这样的东西:

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

Can I exec a ps1 script like this via the scripts object?我可以通过脚本对象执行这样的 ps1 脚本吗? Is any special setup/config required?是否需要任何特殊的设置/配置? Are there any additional constraints?是否有任何额外的限制?

Assuming powershell is in you PATH you can call it like this:假设 powershell 在你的 PATH 中,你可以这样称呼它:

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

Tested on Windows 7 with Powershell v4.在 Windows 7 上使用 Powershell v4 进行测试。

Limitations are that you need Powershell installed and in your PATH.限制是您需要在 PATH 中安装 Powershell。 I didn't test it with Powershell for Linux, so not sure if this solution will be portable to other platform for now.我没有用 Linux 的 Powershell 对其进行测试,所以现在不确定这个解决方案是否可以移植到其他平台。

You might set the script-shell config - either via npm config set script-shell "powershell" or environment variable $env:npm_config_script_shell="powershell"您可以设置脚本外壳配置- 通过npm config set script-shell "powershell"或环境变量$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.我不确定你是否可以提供像 -NoProfile 这样的参数。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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