使用 PowerShell 的 Invoke-Command 进行远程处理时,如何包含本地定义的函数? [英] How do I include a locally defined function when using PowerShell's Invoke-Command for remoting?

查看:92
本文介绍了使用 PowerShell 的 Invoke-Command 进行远程处理时,如何包含本地定义的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我遗漏了一些应该很明显的东西,但我就是不知道该怎么做.

I feel like I'm missing something that should be obvious, but I just can't figure out how to do this.

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

I have a ps1 script that has a function defined in it. It calls the function and then tries using it remotely:

function foo
{
    Param([string]$x)

    Write-Output $x
}

foo "Hi!"

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

这个简短的示例脚本打印嗨!"然后崩溃并说术语‘foo’未被识别为 cmdlet、函数、脚本文件或可运行程序的名称."

This short example script prints "Hi!" and then crashes saying "The term 'foo' is not recognized as the name of a cmdlet, function, script file, or operable program."

我知道该函数未在远程服务器上定义,因为它不在 ScriptBlock 中.我可以在那里重新定义它,但我宁愿不这样做.我想定义一次函数并在本地或远程使用它.有什么好的办法吗?

I understand that the function is not defined on the remote server because it is not in the ScriptBlock. I could redefine it there, but I'd rather not. I'd like to define the function once and use it either locally or remotely. Is there a good way to do this?

推荐答案

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

You need to pass the function itself (not a call to the function in the ScriptBlock).

我上周也有同样的需求,发现 这个SO讨论

I had the same need just last week and found this SO discussion

所以你的代码会变成:

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

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

Note that by using this method, you can only pass parameters into your function positionally; you can't make use of named parameters as you could when running the function locally.

这篇关于使用 PowerShell 的 Invoke-Command 进行远程处理时,如何包含本地定义的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆