Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create PowerShell scriptblock from scriptblock

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 }
}
like image 356
Rob Avatar asked Feb 14 '13 15:02

Rob


1 Answers

This will do the trick for you:

function TwiceAsScriptBlock([scriptblock] $s)
{

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

Powershell Return Scriptblock

like image 92
Musaab Al-Okaidi Avatar answered Nov 03 '22 22:11

Musaab Al-Okaidi