【问题标题】:Powershell script from another script with multiple positional arguments来自具有多个位置参数的另一个脚本的 Powershell 脚本
【发布时间】:2016-11-01 10:01:27
【问题描述】:

已经有一些关于如何调用一个 PS 脚本与另一个类似的参数的问题 Powershell: how to invoke a second script with arguments from a script

但如果我的第一个脚本有多个位置参数,我会卡住。

testpar2.ps1 调用 testpars.ps1

#$arglist=(some call to database to return argument_string)

$arglist="first_argument second_argument third_argument"

$cmd=".\testpars.ps1"

& $cmd $arglist

$arglist 变量应使用数据库中的字符串填充。此字符串包含 testpar.ps1 的参数。

testpars.ps1 看起来像

echo argument1 is $args[0] 
echo argument2 is $args[1] 
echo arugment3 is $args[3]

# some_command_call $arg[0] $arg[1] $arg[2]

这个参数应该以某种方式在 testpars.ps1 中使用,比如将它们路径到某个命令。

但是当我运行 testpars2.ps1 我得到了

argument1 is first_argument second_argument third argument 
argument2 is 
arugment3 is

它认为这是一个论点,而不是它们的列表。

【问题讨论】:

  • echo arugment3 is $args[3] 你是说$args[2]吗?

标签: powershell


【解决方案1】:

如您所见,当您将字符串传递给函数时,PowerShell 将其视为单个值。这通常很好,因为它避免了 CMD 中必须不断引用和取消引用字符串的问题。要获取单独的值,您需要将split() 字符串放入数组中。

$arglistArray = $arglist.split()

现在您有了一个包含三个字符串的数组,但它们仍然作为一个参数传递。 PowerShell 有一个称为splatting 的想法,可以将一组值作为多个参数传递。要使用 splatting,请将参数列表中的 $ 替换为 @

& $cmd @arglistArray

有关喷溅的更多信息,请输入Get-Help about_Splatting

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2019-01-08
    • 2015-07-07
    • 2022-01-23
    • 1970-01-01
    • 2014-11-12
    相关资源
    最近更新 更多