【问题标题】:how to execute powershell ps1 scripts from package.json "scripts"?如何从 package.json“脚本”执行 powershell ps1 脚本?
【发布时间】:2018-03-03 09:22:51
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: node.js powershell npm package.json


    【解决方案1】:

    假设 powershell 在你的 PATH 中,你可以这样称呼它:

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

    在带有 Powershell v4 的 Windows 7 上测试。

    限制是您需要在 PATH 中安装 Powershell。我没有使用 Powershell for Linux 对其进行测试,因此目前不确定此解决方案是否可以移植到其他平台。

    【讨论】:

    • 如果您将@powershell 替换为pwsh 并将-Command 替换为-File,它可以在带有Powershell Core 的Linux / Mac OS X 上运行(参见What's New in PowerShell Core 6.0)。不要在pwsh 之前使用@ 符号,因为它是批处理语法。完整的工作示例是:"test": "pwsh ./Do-Stuff.ps1 -ExecutionPolicy Unrestricted -NoProfile".
    • 很好的答案,适用于我的 Windows 10
    【解决方案2】:

    您可以设置script-shell config - 通过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 这样的参数。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-12
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多