PowerShell Script Arguments passed as an array

EDIT: I changed the code here to a simple test case, rather than a full implementation where this problem occurs.

I am trying to call one Powershell script another, but everything does not work as I expect. As I understand it, the & operator must expand arrays to separate parameters. This is not for me.

caller.ps1

$scriptfile = ".\callee.ps1" $scriptargs = @( "a", "b", "c" ) & $scriptfile $scriptargs 

callee.ps1

 Param ( [string]$one, [string]$two, [string]$three ) "Parameter one: $one" "Parameter two: $two" "Parameter three: $three" 

Running .\caller.ps1 leads to the following output:

 Parameter one: abc Parameter two: Parameter three: 

I think the problem I'm experiencing is that the $scriptargs not expanded and rather passed as a parameter. I am using PowerShell 2.

How can I get caller.ps1 to run callee.ps1 with an array of arguments?

+6
source share
3 answers

When you call your own command, a call like & $program $programargs will correctly exit the array of arguments so that it correctly parses the executable. However, for the PowerShell cmdlet, script, or function, there is no external programming that requires looping / parsing, so the array is passed as-is as a single value.

Instead, you can use splatting to pass the elements of the array (or hash tables) to the script:

 & $scriptfile @scriptargs 

@ in & $scriptfile @scriptargs causes the values ​​in $scriptargs applied to the script parameters.

+9
source

You pass variables as one object, you need to pass them independently.

It works here:

 $scriptfile = ".\callee.ps1" & $scriptfile abc 

So does it:

 $scriptfile = ".\callee.ps1" $scriptargs = @( "a", "b", "c" ) & $scriptfile $scriptargs[0] $scriptargs[1] $scriptargs[2] 

If you need to pass it as a separate object, for example an array, then you can split its script; The specific code for this will depend on the type of data that you are transmitting.

+1
source

Invoke-Expression Cmdlet:

 Invoke-Expression ".\callee.ps1 $scriptargs" 

As a result, you will receive:

 PS > Invoke-Expression ".\callee.ps1 $scriptargs" Parameter one: a Parameter two: b Parameter three: c PS > 
+1
source

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


All Articles