powershell - 使用PowerShell的Invoke-Command进行远程处理时,如何包含本地定义的函数?

标签 powershell powershell-2.0 powershell-remoting

我觉得我缺少一些显而易见的东西,但我只是不知道该怎么做。

我有一个ps1脚本,其中定义了一个功能。它调用该函数,然后尝试远程使用它:

function foo
{
    Param([string]$x)

    Write-Output $x
}

foo "Hi!"

Invoke-Command -ScriptBlock { foo "Bye!" } -ComputerName someserver.example.com -Credential someuser@example.com

这个简短的示例脚本显示“Hi!”。然后崩溃,并说“术语'foo'不被识别为cmdlet,函数,脚本文件或可运行程序的名称”。

我知道该函数未在远程服务器上定义,因为它不在ScriptBlock中。我可以在那里重新定义它,但我不想。我想一次定义该函数,然后在本地或远程使用它。有什么好方法吗?

最佳答案

您需要传递函数本身(而不是ScriptBlock中的函数调用)。

我上周有同样的需求,发现this SO discussion

因此,您的代码将变为:

Invoke-Command -ScriptBlock ${function:foo} -argumentlist "Bye!" -ComputerName someserver.example.com -Credential someuser@example.com

请注意,使用此方法,只能将参数位置传递给函数。您不能像在本地运行函数时那样使用命名参数。

关于powershell - 使用PowerShell的Invoke-Command进行远程处理时,如何包含本地定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367367/

相关文章:

powershell - 进入IF但退出到ELSE

windows - 在 PowerShell 中如何将文件从远程 PSsession 复制到另一台 Windows 服务器

powershell - 到本地主机的 New-PSSession 失败

powershell - 在 Azure 上每小时运行一次 Powershell 脚本

powershell - 如何导出 Azure 订阅上的 "administrators"列表?

powershell - Powershell 2 中的结构或对象

powershell - 在PowerShell脚本中处理命令提示符错误

powershell - 使用 powershell 远程处理安装 Windows 10 应用程序

powershell - 如何使用PowerShell从字符串读取特定变量?

PowerShell 属性表达式将执行时间增加 4-5 倍