Invoke-Command - Pass Reference to Functions on local machine


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?

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.

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 :smiley: ) 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

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

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.