title: Dynamically create PowerShell scriptblock from scriptblock
body: <p>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.</p>
  
  <p>It's easy to write a method to invoke the scriptblock twice.</p>
  
  <pre><code>$x = { write-host "Hello" }
  function DoIt([scriptblock] $s) { $s.Invoke(); }
  function DoItTwice([scriptblock] $s) { $s.Invoke(); $s.Invoke(); }
  
  DoIt($x)
  DoItTwice($x)
  </code></pre>
  
  <p>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</p>
  
  <pre><code>function TwiceAsScriptBlock([scriptblock] $s)
  {
      function twice
      {
          $s.Invoke();
          $s.Invoke();
      }
      return { twice }
  }
  </code></pre>