title: Using Invoke-Command -ScriptBlock on a function with arguments
body: <p>I'm writing a PowerShell script that will execute commands on a remote host using <a href="https://technet.microsoft.com/en-us/library/hh849719.aspx" rel="noreferrer">Invoke-Command</a> and its <code>-ScriptBlock</code> parameter.  For example,</p>
  
  <pre><code>function Foo {
      ...
      return "foo"
  }
  $rv = Invoke-Command --Credential $c --ComputerName $fqdn -ScriptBlock ${function:Foo}
  </code></pre>
  
  <p>This works fine. What I'd like to do now is the same thing, but call a function with local arguments. For example,</p>
  
  <pre><code>function Bar {
      param( [String] $a, [Int] $b )
      ...
      return "foo"
  }
  [String] $x = "abc"
  [Int] $y = 123
  $rv = Invoke-Command --Credential $c --ComputerName $fqdn -ScriptBlock ${function:Foo($x,$y)}
  </code></pre>
  
  <p>But this does not work:</p>
  
  <blockquote>
    <p>Invoke-Command : Cannot validate argument on parameter 'ScriptBlock'.
    The argument is null. Supply a non-null argument and try the command
    again.</p>
  </blockquote>
  
  <p>How can I use Invoke-Command with a <code>-ScriptBlock</code> that is a local function with arguments?</p>
  
  <p>I realize that I can wrap the entire function and the parameters in a big code block, but that is not a clean way of doing it, in my opinion.</p>