How to import custom PowerShell module into the remote session?

I'm developing a custom PowerShell module, which I'd like to use in context of a remote session to a different computer. The following code (which obviously doesn't work) explains what I'm trying to achieve:

import-module .\MyCustomModule.psm1
$session = new-pssession -computerName server01
invoke-command -session $session -scriptblock { 
  <# use function defined in MyCustomModule here #> 
}

The first question is whether it is at all possible to achieve this scenario? I mean I would only like my custom module to be physically present on my machine, not on remote server.

I have found this thread, but I didn't manage it to work - it doesn't allow creating a session from remote machine back to the local one. Probably, I faced with the configuration limitations mentioned somewhere in the comments to that thread... Besides, the author mentioned the performance implications which is critical for my solution...

If that's possible, then how?

The version of PowerShell is currently not a constraint - if the solution is only available in PS 3.0 - I can live with this.

Import-Module (Microsoft.PowerShell.Core), It is very common to create a remote session on a machine and in that session you can then use the modules on that remote server. Another� When you import a CIM module into the local session, PowerShell converts the CDXML files for each command into PowerShell scripts, which appear as functions in the local session. Although Get-Disk is typed in the local session, the cmdlet implicitly runs on the remote computer from which it was imported.

Here's another approach: Recreate the module in a remote session, without copying any files.

I've made no attempt to cope with dependencies between modules, but this seems to work ok for simple self contained modules. It relies on the module being available in the local session, as this makes determining exports easier, but with a bit of extra work it would also work with a module file.

function Import-ModuleRemotely([string] $moduleName,[System.Management.Automation.Runspaces.PSSession] $session)
{
    $localModule = get-module $moduleName;
    if (! $localModule) 
    { 
        write-warning "No local module by that name exists"; 
        return; 
    }
    function Exports([string] $paramName, $dictionary) 
    { 
        if ($dictionary.Keys.Count -gt 0)
        {
            $keys = $dictionary.Keys -join ",";
            return " -$paramName $keys"
        }
    }
    $fns = Exports "Function" $localModule.ExportedFunctions;
    $aliases = Exports "Alias" $localModule.ExportedAliases;
    $cmdlets = Exports "Cmdlet" $localModule.ExportedCmdlets;
    $vars = Exports "Variable" $localModule.ExportedVariables;
    $exports = "Export-ModuleMember $fns $aliases $cmdlets $vars;";

    $moduleString= @"
if (get-module $moduleName)
{
    remove-module $moduleName;
}
New-Module -name $moduleName {
$($localModule.Definition)
$exports;
}  | import-module
"@
    $script = [ScriptBlock]::Create($moduleString);
    invoke-command -session $session -scriptblock $script;
}

[SOLVED] Invoke-Command {Import-Module}, Then I make the module avialable on remote machine with: ls module\*.ps1 | % { Invoke-Command -FilePath $_ -Session $remote_session }. This works but� Once you have installed a module on a system, you will likely want to import the module. Importing is the process that loads the module into active memory, so that a user can access that module in their PowerShell session. In PowerShell 2.0, you can import a newly-installed PowerShell module with a call to Import-Module cmdlet. In PowerShell 3

I don't believe this is supported right of the box without any "hacks". The smart move would probably be to put the module on a public location like a fileserver and import it on the server when you need it. Ex:

$session = new-pssession -computerName server01
invoke-command -session $session -scriptblock {
    #Set executionpolicy to bypass warnings IN THIS SESSION ONLY
    Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
    #Import module from public location
    Import-Module \\fileserver\folders\modulelocation...


    <# use function defined in MyCustomModule here #> 
}

Import PowerShell module from a remote machine, I created a script that works on a local host relying on a custom module from codeplex. I turns out I need to run my script against a remote host� To execute PowerShell commands or scripts on a remote computer, you need to create a session. This is also known as PowerShell remoting and it is just like an SSH session to an operating system. There are several ways to create a PowerShell session. I'll list one of the easiest methods here. These are the required steps. Step 1.

What about making scriptblock out of your custom function and sending it off to terget servers using Invoke-command

Import-module YourModule
$s = [scriptblock]::Create($(get-item Function:\Your-ModuleFunction).Definition)

Invoke-Command -ScriptBlock $s -Computername s1,s2,sn

Import local module in remote session : PowerShell, By locally you mean you log on to the server and import the module there, right? When you do Invoke-command the command is invoked on the remote session� After you have a connection to the PSSession on remote computer, you may export these commands with session details to a module, and when you import this module back, you will be connected to the remote server with the credentials you provided for the session to execute these Cmdlets. The Cmdlet for this action is “Export-PSSession“. It

Thanks for this thread it was helpfull….

But i actually rewrote the function.

Be aware, that nether the original function in this post or this rewritten function includes module manifest data. So you cant rely on version checks on the module.

function Import-ModuleRemotely {
    Param (
        [string] $moduleName,
        [System.Management.Automation.Runspaces.PSSession] $session
    )

    Import-Module $moduleName

    $Script = @"
    if (get-module $moduleName)
    {
        remove-module $moduleName;
    }

    New-Module -Name $moduleName { $($(Get-Module $moduleName).Definition) } | Import-Module
"@

    Invoke-Command -Session $Session -ScriptBlock {
        Param($Script)
        . ([ScriptBlock]::Create($Script))
        Get-Module 
    } -ArgumentList $Script
}

Topic: import-module to remote session, Commands with built-in remoting; PowerShell remoting subsystem; Using and implicit remoting; Remoting considerations and custom remoting sessions; The ultimate goal for remoting is to be able to execute a command on a remote computer. That said, unless you allow random people to install computers on your� The Import-Module cmdlet cannot find the module. To import the module, you must provide the full path to the root module file or module manifest file. Additional features, such as the following, do not work unless the module is imported into the session. In well-formed modules in the PSModulePath environment variable, these features work even

new-pssession and import-module - PowerShell Remoting, Beginning in PowerShell 3.0, modules are imported automatically when any a custom object with members that represent the imported module members. the CIM session connection to import modules from the remote computer into the� Save-Module -Name Az -Path '\\server\share\PowerShell\modules' -Force Troubleshooting. Here are some common problems seen when installing the Azure PowerShell module. If you experience a problem not listed here, file an issue on GitHub. Proxy blocks connection

Push-Module.psm1 1.0, So starting with PowerShell version 3.0, there is a now way to import a module from a remote machine. This is a great improvement when you need to collect data from a list of servers and need to use commands the module to gather it.

Chapter 11. PowerShell remoting,

Comments
  • Duplicate with stackoverflow.com/questions/2830827/… ?
  • I don't believe this is supported right of the box. You'd have to use a hack like they tried. Can I ask why you can't just install the module on the remote computer? That's the smart solution.
  • @DavidBrabant, well, yes, it's quite close. However, I failed to make the solution there work, and I'm referencing that thread explicitly to indicate I tried that option and asking for alternatives :)
  • @Graimer, the idea was to use any out of the available machines to perform some deployment scenarios, without anything required to be installed on a remote machine. But if the scenario is not supported, we'll have to live with this...
  • Why not place the module in a public location, start your scriptblock with Import-Module \\fileserver\folders\modulefolder ? Make sure it's digitally signed or use something like Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process before importing to bypass warnings?
  • Yan, This is a very detailed and through response. Thanks for the info.
  • Good to know it's helpful :)
  • Does anyone know if something has changed in the last 3 years to make this easier?
  • it seems like the main disadvantage with Modules Approach: it opens up a redundancy can-of-worms (inconsistent version of a module/script on each target).
  • This worked great for me the first time I used it unlike some other options. Thanks for contributing this!
  • The issue with this approach will be then overcoming the double hop problem.
  • Wont work because module can reference its own functions.