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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With