首页 > 解决方案 > 将参数从一个 powershell 脚本传递到另一个

问题描述

我有一个 powershell 脚本,比如这个:

$ErrorActionPreference = "Stop"

$WORKDIR=$args[0]

Write-Host "Num of arguments given: " $args.Count

$AllArguments = ""
for ($i = 1; $i -lt $args.Count; $i += 2) {
    $AllArguments = '$AllArguments $args[$i] "$($args[$i+1])"'
}

Write-Host "AllArguments: $($AllArguments)"

Write-Host "Starting .\someotherscript.ps1 in directory $($WORKDIR)"

pushd "$WORKDIR"

& Powershell -File .\someotherscript.ps1 $AllArguments

popd 

基本上,这个 powershell 脚本应该启动另一个 powershell 脚本,但没有第一个参数。因此,例如,当此脚本以 启动时.\firstscript.ps1 C:\some\dir -GiveMeParameter param1,它应该使用以下参数调用另一个脚本.\someotherscript.ps1 -GivMeParameter param1

如何做到这一点?目前我不知道如何解决这个问题。

标签: powershelljenkins

解决方案


您可以使用多重赋值来提取第一个和剩余的参数,方法是

$WORKDIR, $RemainingArgs = $args

我不确定您为什么再次调用 PowerShell 来运行脚本。您可以直接运行脚本并使用splatting将剩余的参数传递给子脚本。

.\someotherscript.ps1 @RemainingArgs 

推荐阅读