Invoke-Command - Pass Reference to Functions on local machine

This topic contains 4 replies, has 3 voices, and was last updated by  Romiko Derbynew 4 months, 2 weeks ago.

  • Author
  • #88960

    Romiko Derbynew


    I have a custom module with my own functions. I do not want to install these modules on the remote machine. So I figured a way to pass the function reference and not a call to the function. Here is the working command:

    Invoke-Command -Session $session -Scriptblock ${function:Set-RPSQLFirewall} -ArgumentList $SQLInstancePort

    However, I had to put a $ sign in front of the ScriptBLock. Why does it need this when sending a reference to a local function?

  • #88963

    Don Jones

    Because the function: drive on the remote server wouldn't contain your function. Normally whatever is in that script block is passed to the remote machine without interpretation, so the remote machine runs it.

    The $ is PowerShell's execution operator; it executes the script block on your machine, and the results of that – now containing the function – are sent to the remote machine.

    • #88970


      I think you are thinking about $() -> subexpression or & -> call operator. What OP does is simply a variable, no scriptblock invocation is involved.

    • #89002

      Romiko Derbynew

      Hey Don,

      Thanks for the info. I really like this feature, a great way to get things done without having custom modules installed on the servers being provisioned.

  • #88964


    The ${} is an escape sequence that you can use to call a variables that contains characters that are not normally allowed in variable names. ( we had a lot of fun with this in here 😀 ) The function: is a way of accessing functions via variables, much like doing $env:computername ( or in your case ${env:computername} )

    What you are doing is equivalent of (Get-Command Set-RPSQLFirewall).Definition

You must be logged in to reply to this topic.