I'm getting mixed results with the availability of custom functions within custom modules, on remote computers, depending on how I load the module. Detail is as followed:
I've written a custom module, within which there is a singular function file. The structure is as followed:
In order to rely on module auto-loading, I modify $env:PSModulePath to contain "C:\PowerShell-Modules\".
In my script (e.g. PassRemote.ps1), "MyFunction" is available and runs as expected. However when trying to run this on a remote computer:
Invoke-Command -ComputerName $computername -UseSSL -ScriptBlock ${function:MyFunction} -ArgumentList $arg1
... it fails, reporting that the cmdlet/function is not recognised.
The only way that I can get the custom function to be passed, is to explicitly load the module within the script. To be clear, I need to write the line:
Import-Module ModuleName
within the parent script (PassRemote.ps1). Only then can the function be passed to the remote session.
Is this a scope issue?
It appears that explicitly loading a module also loads the entire contents of the functions/cmdlets within it (i.e. the code itself). As such, functions are available to be passed in their entirety.
When relying on auto-loading of modules, only the names of available cmdlets/functions are loaded (obviously, otherwise PS3+ would take quite a while to load on start up). This means that whilst the PS session is "aware" of the auto-loaded functions, at that point it doesn't actually have the code to pass to the remote session. Sadly using "-ScriptBlock ${function:MyFunction}" does not seem to forcefully expand or load this function in order for it to be available to pass.
To prove the above theory (and avoid explicitly loading the module), we can run:
$x = Get-Command MyFunction
and then:
Invoke-Command -ComputerName $computername -UseSSL -ScriptBlock ${function:MyFunction} -ArgumentList $arg1
It would be nice if there was some way to do this within the Invoke-Command line but I think this might be why I was experiencing the above scenarios.