来自另一个具有多个位置参数的脚本的Powershell脚本

时间:2016-06-29 15:26:07

标签: powershell

关于如何使用来自另一个PS脚本的参数调用一个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

它认为它是一个参数,而不是它们的列表。

1 个答案:

答案 0 :(得分:1)

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

$arglistArray = $arglist.split()

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

& $cmd @arglistArray

有关splatting的更多信息,请键入Get-Help about_Splatting

相关问题