简体   繁体   English

从scriptblock动态创建PowerShell脚本块

[英]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. 我想写一个powershell函数,它通过基于作为输入参数传入的scriptblock动态创建一个scriptblock来返回一个scriptblock。 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. 编写一个返回脚本块的方法更加困难,该脚本块具有两次调用(输入)scriptblock的效果。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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