views:

3412

answers:

3

Hi,

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.

+2  A: 
# use the pipe, Luke!

file1.ps1
---------
$args | write-host
$args | .\file2.ps1    

file2.ps1
---------
process { write-host $_ }
Richard Berg
+9  A: 

This is complicated in V1 but 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.

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.

-bruce

Bruce Payette Microsoft

A: 

Both the solutions above work ..

Thanks Bruce and Thanks Richard.