如何同时(并行)在远程计算机上调用-命令相同的功能 [英] How to Invoke-Command the same function on remote computers in the same time (parallel)

查看:71
本文介绍了如何同时(并行)在远程计算机上调用-命令相同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,该脚本具有多个需要时间在不同远程计算机上执行的函数.有什么办法可以同时以并行方式调用-命令它们吗?一个例子将不胜感激.谢谢

I'm working on a script that has several functions that take time to execute on different remote computers. Is there any way I could Invoke-Command them in the same time in a parallel way? An example would be appreciated. Thanks

推荐答案

Invoke-Command 已经对每台计算机并行执行调用,作为内置功能的一部分:

Invoke-Command already executes calls against each computer in parallel, as part of built-in functionality:

一对多远程处理

远程处理的真正威力在于能够并行地向一台或多台远程计算机发送命令.每台远程计算机执行命令,将结果对象序列化为 XML,并通过网络将结果传输到您的计算机.

您的计算机接收 XML 并将其反序列化回静态对象.这使您可以像处理任何其他命令输出一样处理命令输出.

这一切都始于 Invoke-Command cmdlet.以最简单的形式,您只需以脚本块的形式指定要运行的命令,以及运行该命令的一台或多台计算机.例如,要从文本文件中读取计算机名称列表(每行一个名称)并对每个名称运行命令,请使用:

Invoke-Command –scriptblock { Get-EventLog Security –newest 200 } –computername (Get-Content computernames.txt)

当结果进入您的计算机时,它们将附加一个名为 PSComputerName 的附加属性.这让您可以看到哪个结果来自哪台计算机.这很有用,因为它们可能不会以相同的顺序收到.

-ComputerName 参数可以接受一个列表/数组,它将并行执行远程命令(而不是一次执行一个).如果要针对正在进行的会话执行多个命令,您还可以使用 -Session 参数.

The -ComputerName parameter can take a list/array, and it will execute a remote command against them in parallel (as opposed to doing them one at a time). You can also use the -Session parameter if wanting to execute multiple commands against ongoing sessions.

注意:请记住,默认情况下,一次限制为 32 个并发连接.这可以通过 -ThrottleLimit 参数修改.

Note: Keep in mind, that this is throttled to 32 concurrent connections at a time, by default. This can be modified via the -ThrottleLimit parameter.

要对远程系统执行本地函数,您必须使用一个小技巧:

To execute local functions against remote systems, you have to use a little trick:

# Let's say the function is called 'Do-Thing'
$Computers = 'node1','node2'
Invoke-Command -ComputerName $Computers -ScriptBlock ${function:Do-Thing} -ArgumentList 'arg1'

不过,将函数/脚本简单地保存到要执行的文件中可能会更容易:

Though, it would likely be easier to simply save the functions/script into a file to be executed:

Invoke-Command -ComputerName $Computers -FilePath .\script.ps1

进一步跟进:

Update-Help
help Invoke-Command -Full
help about_Remote

如果需要,请查看以下链接:

Checkout the following links if needed:

这篇关于如何同时(并行)在远程计算机上调用-命令相同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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