简体   繁体   中英

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 }
}

This will do the trick for you:

function TwiceAsScriptBlock([scriptblock] $s)
{

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

Powershell返回Scriptblock

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM