在远程计算机上运行本地功能?

时间:2013-04-12 19:31:22

标签: powershell powershell-remoting

我的电脑上有一个简单的功能

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

我想在远程计算机上运行它

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

可以理解,OTHERPC上不存在Do-Stuff,但这不起作用。我怎么能让它工作呢? Do-Stuff函数抽象了一些基本代码,并在其他几个地方调用,所以我不想复制它。

请注意,在我的示例中,值通过参数和范围闭包传递给函数。这可能吗?

3 个答案:

答案 0 :(得分:9)

我不知道你如何使用闭包值,但你可以将两者作为参数传递:

$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

答案 1 :(得分:4)

不确定是否还有人关心,但您实际上可以通过PSSession将保存在.ps1文件中的自定义函数加载到远程计算机。我尝试了它,它对我有用。 Check out this guy's solution

答案 2 :(得分:1)

有人真正关心的风险更小:),但这是一种做法。

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" }
相关问题