首页 > 解决方案 > 需要帮助将带有参数的函数传递和执行到脚本块中以远程执行它

问题描述

我正在编写一个使用函数来处理数据操作的应用程序。此时我需要在远程计算机上执行一个使用此函数并将其作为参数接收的脚本块。我正在测试的代码完成了这一点,但它会抛出错误以及正确的结果。需要一种方法来完成相同的结果而不会出错。

   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>

标签: functionpowershellpowershell-5.0invoke-commandscriptblock

解决方案


直接传递 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

推荐阅读