function - 需要帮助将带有参数的函数传递和执行到脚本块中以远程执行它
问题描述
我正在编写一个使用函数来处理数据操作的应用程序。此时我需要在远程计算机上执行一个使用此函数并将其作为参数接收的脚本块。我正在测试的代码完成了这一点,但它会抛出错误以及正确的结果。需要一种方法来完成相同的结果而不会出错。
function MyFunction{
param ($String)
Write-Host "this is: $String"
}
$ScriptBlock = {
param ($MyFunction, $String)
invoke-expression $MyFunction.ScriptBlock.Invoke($String)
}
$MyFunction = (get-item function:MyFunction)
$String = "123"
Invoke-Command -ComputerName <RemoteComputerName> -ScriptBlock $ScriptBlock -
Credential $DomainCred -ArgumentList ($MyFunction,$String)
这是我收到的结果 - 部分结果加上错误
this is: 123
Cannot convert '' to the type 'System.String' required by parameter 'Command'. Specified method is not supported.
+ CategoryInfo : InvalidArgument: (:) [Invoke-Expression], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.InvokeExpressionCommand
+ PSComputerName : <RemoteComputerName>
解决方案
直接传递 ScriptBlock 定义,而不是通过返回的 FunctionInfo 对象Get-Item function:\MyFunction
:
$ScriptBlock = {
param(
[ScriptBlock]$MyFunction,
[string]$String
)
$MyFunction.Invoke($String)
}
Invoke-Command -ComputerName <RemoteComputerName> -ScriptBlock $ScriptBlock -ArgumentList ${function:myfunction},$string
推荐阅读
- oracle - 子查询问题
- r - 如果数据框中存在列,则重命名列 - 使用 if else 的管道运算符
- javascript - 开玩笑测试会影响其他测试
- mysql - 合并补丁json数组项?
- pandas - 生成具有相同键但不同值的数据框
- amazon-web-services - AWS ECS 部署的 ResourceInitializationError
- javascript - Ramda — 根据允许列表切换对象的属性
- .net - 在 f# 中使用自定义函数相交
- python - 在 Python 中将 XLSX 转换为 CVS:保留值,而不是公式
- python - meson 找到 python3 二进制文件,找不到 python3 依赖项