Passing around command line $args in powershell , from function to function

arguments, command-line, nested, powershell

Solution

In PowerShell V2, it's trivial with splatting. bar just becomes:

function bar { foo @args }

Splatting will treat the array members as individual arguments instead of passing it as a single array argument.

In PowerShell V1 it is complicated, there's a way to do it for positional arguments. Given a function foo:

function foo { write-host args0 $args[0] args1 $args[1] args2 $args[2]   }

Now call it from bar using the `Invoke()` method on the scriptblock of the foo function

function bar { $OFS=',';  "bar args: $args";  $function:foo.Invoke($args) }

Which looks like

PS (STA) (16) > bar 1 2 3

bar args: 1,2,3

args0 1 args1 2 args2 3

when you use it.

Problem

This is a nasty issue I am facing. Wont be surprised if it has a simple solution, just that its eluding me. I have 2 batch files which I have to convert to powershell scripts. ``` file1.bat --------- echo %1 echo %2 echo %3 file2.bat %* file2.bat -------- echo %1 echo %2 echo %3 ``` On command line, I invoke this as C:> file1.bat one two three The output I see is as expected one two three one two three (This is a crude code sample) When I convert to Powershell, I have ``` file1.ps1 --------- Write-Host "args[0] " $args[0] Write-Host "args[1] " $args[1] Write-Host "args[2] " $args[2] . ./file2.ps1 $args file2.ps1 --------- Write-Host "args[0] " $args[0] Write-Host "args[1] " $args[1] Write-Host "args[2] " $args[2] When I invoke this on powershell command line, I get $> & file1.ps1 one two three args[0] one args[1] two args[2] three args[0] one two three args[1] args[2] ``` I understand this is because $args used in file1.ps is a System.Object[] instead of 3 strings. I need a way to pass the $args received by file1.ps1 to file2.ps1, much the same way that is achieved by %* in .bat files. I am afraid, the existing manner will break even if its a cross-function call, just the way its a cross-file call in my example. Have tried a few combinations, but nothing works. Kindly help. Would much appreciate it.

Original source