0

I wish to pass "Write-Host mm" as script block to function "f", and I hope "f" will execute it 10 times, so I tried:

    function f([ScriptBlock]$s)
    {
        1..10|$s
    }
    f(Write-Host mm)

Unfortunately, powershell gives error:

    At C:\Users\engineer\Documents\Untitled1.ps1:3 char:11
    +     1..10|$s
    +           ~~
    Expressions are only allowed as the first element of a pipeline.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline
    How to correct my script?

Thanks for Jason's first answer, but seems doesn't work: Thanks, but seems this doesn't work, I've got PS 4.0 and

function f([ScriptBlock]$s)
{
    1..10 | & $s
}
f { Write-Host mm }

Execute this script and it prints out: Thanks, but seems this doesn't work, I've got PS 4.0 and

d:\ > function f([ScriptBlock]$s)
{
    1..10 | & $s
}
f { Write-Host mm }
mm

This is strange! A script prints out itself! I've got PS4.0 and running ISE. Why is that?

vik santata
  • 2,989
  • 8
  • 30
  • 52

2 Answers2

2

You are trying to execute your scriptblock 10 times, but instead you try to pipe in an array from 1 to 10. You should pipe that array to foreach-object instead.

function f([ScriptBlock]$s)
{
    1..10 | % {& $s}
    # % is an alias for Foreach-Object
}
f { Write-Host mm }
Vesper
  • 18,599
  • 6
  • 39
  • 61
0

You need to use the invocation operator &. Also, script blocks are enclosed in curly braces, so your example would be:

function f([ScriptBlock]$s)
{
    1..10 | & $s
}
f { Write-Host mm }

Note that you don't call PowerShell functions like you would a C# method - you don't use parentheses around the arguments, you call PowerShell functions like commands, with spaces between arguments.

Jason Shirk
  • 7,734
  • 2
  • 24
  • 29