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?

2 Answers 2

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 }
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

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 } mm
Why it just prints out the script itself? It's really strange.
@viksantata Does it print "mm", "Write-Host mm" or "function f(..."?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.