1

I am writing an application that uses a function to handle data manupilation. At this point I need to execute a scriptblock on the remote computer that uses this function and receves it as a parameter. The code I am testing accomplishes this, but it throws back and error along with the correct result. Need a way to accomplish the same result without the error.

   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 the result I am receiving - part result plus error

    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>
russ12345
  • 11
  • 3
  • Why not just pass the function as the `ScriptBlock` argument directly? – Mathias R. Jessen May 16 '19 at 13:12
  • because the scriptblock does a lot more processing then just the function. The functions does tiny piece of work and actually there are 4 more functions that I will need to pass in there as well. They are all Global to the script, but since this execution is a scriptblock on a remote server, local global functions can't get there implicitly. – russ12345 May 16 '19 at 13:21

2 Answers2

0

Pass the ScriptBlock definition directly, rather than the FunctionInfo object returned by Get-Item function:\MyFunction:

$ScriptBlock = {
  param(
    [ScriptBlock]$MyFunction,
    [string]$String
  )

  $MyFunction.Invoke($String)
}
Invoke-Command -ComputerName <RemoteComputerName> -ScriptBlock $ScriptBlock -ArgumentList ${function:myfunction},$string
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • this does not work, It only throws an error: Cannot process argument transformation on parameter 'MyFunction'. Cannot convert the " param ($String) Write-Host "this is: $String" – russ12345 May 16 '19 at 14:45
0

Solution Found thanks to powershell.org

replace in scriptblock

    invoke-expression $MyFunction.ScriptBlock.Invoke($String)  

             with

   [ScriptBlock]::Create($MyFunction.ScriptBlock).Invoke($String)
russ12345
  • 11
  • 3