Question:
I have a simple function on my computer
1 2 3 4 5 6 |
MYPC> $txt = "Testy McTesterson" MYPC> function Do-Stuff($file) { cd c:\temp; $txt > $file; } |
I would like to run it on a remote computer
1 2 |
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?
Answer:
I don’t know how you use the closure value, but you can pass both as parameters like so:
1 2 3 4 5 |
$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 |