8

I want to use Powershell in order to call a batch file on remote machines. This batch file has arguments. Here's what I have so far:

$script = "\\fileshare\script.cmd"
$server = $args[0]
$args [string]::join(',',$args[1 .. ($args.count-1)])

Invoke-Command -computername $server {$script + ' ' + $args}

After a bit of searching, I found that the Invoke-Command function runs its scriptblock in a whole new process, so you can't put variables in it (they won't get expanded). That's what the -ArgumentList tag is for. So I tried this instead...

Invoke-Command -computername $server {\\fileshare\script.cmd} -ArgumentList "FirstArgument"

That didn't work either... my batch script tells me it's not being passed any arguments. I can't find anything that explicitly says so, but it looks like the -ArgumentList parameter only works on Powershell scripts (it won't feed them to a batch script).

Any ideas how I can use Invoke-Command to call a batch file with arguments?

Jay Spang
  • 2,013
  • 7
  • 27
  • 32

2 Answers2

8

When you pass the argument list to the scriptblock, try to "receive them" using a PARAM directive. Like this:

Invoke-Command -computername $server {PARAM($myArg) \\fileshare\script.cmd $myArg} -ArgumentList "FirstArgument"

or you can just use the $args automatic variable:

Invoke-Command -computername $server {\\fileshare\script.cmd $args} -ArgumentList "FirstArgument"
zdan
  • 28,667
  • 7
  • 60
  • 71
  • Thanks that did it! That's even what it says to do on the technet documentation for Invoke-Command, so I'm a bit ashamed I couldn't figure it out on my own! That little bit about $args is helpful though. – Jay Spang Dec 17 '11 at 18:33
3

The arguments will be passed as arguments to the scriptblock and not directly to your cmd. You have to do:

Invoke-Command {param($script,$arg1) &$script $arg1 } -computername $server -ArgumentList $script,"FirstArgument"

or

Invoke-Command {&$args[0] $args[1] } -computername $server -ArgumentList $script,"FirstArgument"

PS: I don't know what you are doing with $args [string]::join(',',$args[1 .. ($args.count-1)]), it is a syntax error

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • This little snippet of code is meant to replicate Perl's 'shift' function. It doesn't seem to cause a compiler error for me, and works as intended. $server = $args[0] $args [string]::join(',',$args[1 .. ($args.count-1)]) – Jay Spang Dec 17 '11 at 18:34
  • Whoops, the '=' was dropped from the second line somehow when I pasted it into the question. – Jay Spang Dec 18 '11 at 00:08
  • Can I use named parameters ? any sample about it ? – Kiquenet Jun 05 '12 at 09:24