Question:
I have been unable to create a Powershell function that accepts more than one scriptblock parameter. Here’s the simplified test script. What is the issue with multiple scriptblocks?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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 produces the following output:
1 2 3 4 |
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". |
Answer:
Your problem is that you are using parentheses and commas when calling functions, a common mistake in powershell.
These should work:
1 2 3 4 |
Task1 {write-host "hello" -nonewline } Task1 {write-host " world" } Task2 {write-host "hello" -nonewline } { write-host " world" } |