脚本编程:Powershell:Powershell Function参数使用技巧(2):在远程计算上运行本地Function
大约 2 分钟
前言
Powrshell自带的很多Function都支持远程执行,例如Restart-Computer
支持参数Computer
指定远程计算机或是本地系统实现远程重启计算机。
我们自定义的Function要实现在远程计算机上执行,则可以借用Invoke-Command
来实现。
正文
- 1、使用
Invoke-Command
来执行本地Function。 举例:
#自定义函数
Function MyFunction {
[CmdletBinding()]
Param (
[Parameter(Position = 1)] #显式指定参数位置,第2个参数。如果不显式指定,默认按定义顺序排序
[String] $Message,
[Parameter(Position = 0)] #显式指定参数位置,第1个参数
[Int]$Count
)
"Say $Message for $Count times." | Out-File C:\AdminPack\PSRemoteExec.log
}
#在远程计算机上执行本地Function "MyFunction", 使用ArugementList指定参数值列表
Invoke-Command -ComputerName "Remote_Computer_Name" -ScriptBlock ${Function:MyFunction} -ArgumentList 5,"Hello"
注意语法
ScriptBlock的参数值${Function:MyFunction}是一个代码块,花括号的内部和左右都不能有任何空格。
扩展
- 也可以使用
Invoke-Command
来实现Function的内部远程执行能力。 举例:
#自定义函数
Function MyFunction {
[CmdletBinding()]
Param (
[Parameter(Position = 1)] #显式指定参数位置,第2个参数。如果不显式指定,默认按定义顺序排序
[String] $Message,
[Parameter(Position = 0)] #显式指定参数位置,第1个参数
[Int]$Count,
[Parameter(Position = 2)] #显式指定参数位置,第3个参数
[String]$ComputerName=$env:COMPUTERNAME
)
#在远程计算机上执行Get-Process
Invoke-Command -ComputerName $ComputerName -ScriptBlock { Get-Process -Name explorer}
}
#使用
MyFunction -ComputerName "Remote_Computer_Name"