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" } It is understood that Do-Stuff does not exist on OTHERPC, and this does not work. How could I make it work? The Do-Stuff function abstracts the base code and is called in several other places, so I do not want to duplicate it.
Please note that in my example, the values ββare passed to the function both through the parameter and through closing the area. Is it possible?
I do not know how you use the closing value, but you can pass both parameters as follows:
$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 Not sure if anyone is still worried, but you can really download your custom functions saved in a .ps1 file to a remote computer via PSSession. I tried and it works for me. See this guy's solution
There is even less risk that someone really cares :), but here is one way to do this.
MYPC> $myPCscript = @' $txt = "Testy McTesterson" function Do-Stuff($file) { cd c:\temp $txt > $file } '@ MYPC> Invoke-Command -ComputerName OTHERPC { Invoke-Expression $using:myPCscript; Do-Stuff "test.txt" }