1

There are already some questions about how to call one PS script with arguments from another like that one Powershell: how to invoke a second script with arguments from a script

But I'm stuck in case I have first script with multiple positional parameters.

testpar2.ps1 calls testpars.ps1

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

$arglist="first_argument second_argument third_argument"

$cmd=".\testpars.ps1"

& $cmd $arglist

$arglist variable should be populated with string from database. This string contains arguments for testpar.ps1.

testpars.ps1 looks like

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

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

This arguments should be used in testpars.ps1 in some way, like to path them to some command.

But when i run testpars2.ps1 i got

argument1 is first_argument second_argument third argument 
argument2 is 
arugment3 is

It thinks that it is one argument, not a list of them.

Community
  • 1
  • 1

1 Answers1

1

As you can see, when you pass a string to a function, PowerShell treats that as a single value. This is usually good, because it avoids the problem in CMD of having to constantly quote and unquote strings. To get separate values, you need to split() the string into an array.

$arglistArray = $arglist.split()

Now you have an array of three strings, but they're still all passed as one parameter. PowerShell has an idea known as splatting to pass an array of values as multiple arguments. To use splatting, replace the $ with @ in the argument list.

& $cmd @arglistArray

For more information on splatting, type Get-Help about_Splatting

Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54