Invoke-Command - Pass Reference to Functions on local machine

Welcome Forums General PowerShell Q&A Invoke-Command - Pass Reference to Functions on local machine

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
1 year ago.

  • Author
    Posts
  • #88960

    Participant
    Points: 0
    Rank: Member

    Hi,

    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

    Keymaster
    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    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

      Participant
      Points: -19
      Rank: Member

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

    • #89002

      Participant
      Points: 0
      Rank: Member

      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

    Participant
    Points: -19
    Rank: Member

    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 http://jakubjares.com/2017/12/09/using-emojis-in-powershell-code/ 😀 ) 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

The topic ‘Invoke-Command - Pass Reference to Functions on local machine’ is closed to new replies.