5

I want to write a powershell function that returns a scriptblock by creating one dynamically based on a scriptblock passed in as an input parameter. I don't seem to be having much luck.

It's easy to write a method to invoke the scriptblock twice.

$x = { write-host "Hello" }
function DoIt([scriptblock] $s) { $s.Invoke(); }
function DoItTwice([scriptblock] $s) { $s.Invoke(); $s.Invoke(); }

DoIt($x)
DoItTwice($x)

It's harder to write a method that returns a scriptblock that has the effect of invoking the (input) scriptblock twice. The following doesn't work

function TwiceAsScriptBlock([scriptblock] $s)
{
    function twice
    {
        $s.Invoke();
        $s.Invoke();
    }
    return { twice }
}

1 Answer 1

10

This will do the trick for you:

function TwiceAsScriptBlock([scriptblock] $s)
{

    $ScriptBlock = [System.Management.Automation.ScriptBlock]::Create("$s ; $s")
    Return $ScriptBlock 
}

Powershell Return Scriptblock

Sign up to request clarification or add additional context in comments.

4 Comments

I tried variants along these lines. If I call Invoke() on the scriptblock returned, I get the following error: TwiceAsScriptBlock : Cannot process argument transformation on parameter 's'.
It worked for me, I'll put a screenshot. What version of powersehll are you running?
check the updated answer, As you can see when I Invoke the new scriptblock it output the message twice.
Ok - think I've been staring at this too long. I was trying TwiceAsNewScriptBlock($x).Invoke() - which is why I thought it didn't work. Thanks!

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.