Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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 }
}
share|improve this question
up vote 4 down vote accepted

This will do the trick for you:

function TwiceAsScriptBlock([scriptblock] $s)
{

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

Powershell Return Scriptblock

share|improve this answer
    
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'. – Rob Feb 14 '13 at 16:17
    
It worked for me, I'll put a screenshot. What version of powersehll are you running? – Musaab Al-Okaidi Feb 14 '13 at 16:19
    
check the updated answer, As you can see when I Invoke the new scriptblock it output the message twice. – Musaab Al-Okaidi Feb 14 '13 at 16:23
    
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! – Rob Feb 14 '13 at 17:19
    
No worries. Glad that I can help. – Musaab Al-Okaidi Feb 14 '13 at 18:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.