Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a local function on a remote computer?

I have a simple function on my computer

MYPC> $txt = "Testy McTesterson"
MYPC> function Do-Stuff($file) { 
  cd c:\temp; 
  $txt > $file; 
}

I would like to run it on a remote computer

MYPC> Invoke-Command -ComputerName OTHERPC { Do-Stuff "test.txt" }

Understandably, Do-Stuff does not exist on OTHERPC and this does not work. How could I get it to work though? The Do-Stuff function abstracts some basic code and is invoked in a few other places so I don't want to duplicate it.

Notice that in my example values are passed into the function both via a parameter and via scope closure. Is that possible?

like image 477
George Mauer Avatar asked Dec 07 '22 08:12

George Mauer


1 Answers

I don't know how you use the closure value, but you can pass both as parameters like so:

$txt = "Testy McTesterson"
$file = "SomeFile.txt"
function Do-Stuff { param($txt,$file) cd c:\temp; $txt > $file }
Invoke-Command -ComputerName SomeComputer -ScriptBlock ${function:Do-Stuff} -ArgumentList $txt, $file
like image 183
dugas Avatar answered Dec 12 '22 19:12

dugas