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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With