function Do-Stuff($file...">

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?

+4
source share
3 answers

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 
+8
source

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

+4
source

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" } 
+1
source

All Articles