How to save a list of parameters in a variable

I have a script internal.ps1 that accepts certain parameters:

 param ($paramA, $paramB) Write-Host $PSBoundParameters 

And the script caller.ps1 that calls it:

 .\internal -paramA A -paramB B 

It works great:

 PS C:\temp> .\caller [paramA, A] [paramB, B] <<<< bounded to both params 

However, in the caller, I want to save the internal parameters to var and use it later. However, this does not work:

 $parms = "-paramA A -paramB B" # Later... .\internal $parms Result: [paramA, A -paramB B] <<<<< All got bounded to ParamA 

Also not using an array:

 $parms = @("A", "B") # Later... .\internal $parms Result: [paramA, System.Object[]] <<<< Again, all bound to ParamA 

How can i do this? Please note that the actual command line is more complex and may have an unknown length.

+4
source share
3 answers

The operator (@) should do what you need. First, consider this simple function:

 function foo($a, $b) { "===> $a + $b" } 

A call with explicit arguments gives what you expect:

 foo "hello" "world" ===> hello + world 

Now put these two values ​​in an array; passing through a normal array gives incorrect results, as you noticed:

 $myParams = "hello", "world" foo $myParams ===> hello world + 

But instead, split the array and get the desired result:

 foo @myParams ===> hello + world 

This works for both scripts and functions. Returning to your script, here is the result:

  .\internal @myParams [paramA, hello] [paramB, world] 

Finally, this will work for an arbitrary number of parameters, so you need to know a priori knowledge about them.

+5
source

powershell -file c:\temp\test.ps1 @("A","B")

or

powershell -command "c:\temp\test.ps1" A,B

0
source

Your script expects 2 arguments, but your previous attempts only pass one (string and array respectively). Do it like this:

 $parms = "A", "B" #... .\internal.ps1 $parm[0] $parm[1] 
0
source

Source: https://habr.com/ru/post/1487022/


All Articles