簡體   English   中英

需要幫助將帶有參數的Function傳遞並執行到Scriptblock中以遠程執行它

[英]Need help to pass and execute Function with arguments into of a Scriptblock to execute it remotely

我正在編寫一個使用函數來處理數據操作的應用程序。 此時,我需要在使用此功能並將其作為參數接收的遠程計算機上執行腳本塊。 我正在測試的代碼可以完成此操作,但是它會拋出錯誤和錯誤,並給出正確的結果。 需要一種方法來實現相同的結果而不會出錯。

   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定義,而不傳遞Get-Item function:\\MyFunction返回的FunctionInfo對象:

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

  $MyFunction.Invoke($String)
}
Invoke-Command -ComputerName <RemoteComputerName> -ScriptBlock $ScriptBlock -ArgumentList ${function:myfunction},$string

通過powershell.org找到解決方案

在腳本塊中替換

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

             with

   [ScriptBlock]::Create($MyFunction.ScriptBlock).Invoke($String)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM