如何从package.json"脚本"执行powershell ps1脚本?

use*_*495 14 powershell node.js npm package.json

如何从package.json"脚本"执行PowerShell ps1脚本?

我知道如何在package.json"scripts"中设置基本脚本.例如,使用以下配置,我可以执行"npm run test",它将向控制台输出"这只是一个测试":

"脚本":{"test":"echo \"这只是一个测试\""}

但是,我有一个更高级的场景,我想执行PowerShell脚本.像这样的东西:

"scripts": {
  "test": "echo \"this is only a test\""
}
Run Code Online (Sandbox Code Playgroud)

我可以通过脚本对象执行这样的ps1脚本吗?是否需要任何特殊的设置/配置?还有其他限制吗?

bar*_*ski 23

假设powershell在你的PATH中,你可以像这样调用它:

"scripts": {
    "test": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./test.ps1"
}
Run Code Online (Sandbox Code Playgroud)

使用Powershell v4在Windows 7上进行了测试.

限制是您需要安装Powershell并在PATH中.我没有用Powershell for Linux测试它,所以不确定这个解决方案现在是否可以移植到其他平台.

  • 如果将 `@powershell` 替换为 `pwsh` 并将 `-Command` 替换为 `-File`,它可以在带有 Powershell Core 的 Linux / Mac OS X 上运行(请参阅 [PowerShell Core 6.0 中的新增功能](https://docs.microsoft) .com/en-US/powershell/scripting/whats-new/what-s-new-in-powershell-core-60?view=powershell-6#renamed-powershellexe-to-pwshexe))。不要在 `pwsh` 之前使用 `@` 符号,因为它是批处理语法。完整的工作示例是:`"test": "pwsh ./Do-Stuff.ps1 -ExecutionPolicy Unrestricted -NoProfile"`。 (3认同)

kas*_*kas 7

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

"command": "powershell Remove-Item ..\\folder\\file; Copy-Item -Path folder\\* -Destination ..\\other-folder -Recurse",
Run Code Online (Sandbox Code Playgroud)
"buildAngular": "powershell buildAngular.ps1"
Run Code Online (Sandbox Code Playgroud)


Jef*_*Son 5

您可以设置script-shell 配置- 通过npm config set script-shell "powershell"或环境变量$env:npm_config_script_shell="powershell"

然后你可以使用

"scripts": {
    "test": "Write-Host 'this is only a test'"
}
Run Code Online (Sandbox Code Playgroud)

或者

"scripts": {
    "buildAngular": ".\\buildAngular.ps1"
}
Run Code Online (Sandbox Code Playgroud)

我不确定你是否可以提供像 -NoProfile 这样的参数。