Powershell function with multiple script block parameters

I was unable to create a Powershell function that takes more than one scriptblock parameter. Here's a simplified test script. What is the problem with multiple scenarios?

function Task1 { param([scriptblock]$f={}) $f.Invoke() } function Task2 { param([scriptblock]$f={}, [scriptblock]$k={}) $f.Invoke() $k.Invoke() } Task1({write-host "hello" -nonewline }) Task1({write-host " world" }) Task2({write-host "hello" -nonewline }, { write-host " world" }) 

This leads to the following conclusion:

 hello world Task3 : Cannot process argument transformation on parameter 'f'. Cannot convert the "System.Object[]" value of type "S ystem.Object[]" to type "System.Management.Automation.ScriptBlock". 
+4
source share
2 answers

Your problem is that you use parentheses and commas when calling functions, which is a common error in powershell.

They should work:

 Task1 {write-host "hello" -nonewline } Task1 {write-host " world" } Task2 {write-host "hello" -nonewline } { write-host " world" } 
+10
source

You can also call the script block with the PowerShell call operator '&'. As an alternative, I deleted the type information and initialized these parameters. This will lead to various errors if the script block is not transmitted.

 function Task1 { param($f) & $f } function Task2 { param($f,$k) & $f & $k } Task1 {write-host "hello" -nonewline } Task1 {write-host " world" } Task2 {write-host "hello" -nonewline } { write-host " world" } 
+3
source

All Articles