Since PS 5.0, I think there is now another cleaner way:
Utilise Copy-Item's ToSession parameter to copy the local module to the remote machine.
This doesn't involve the disadvantages of previous solutions:
- No need to copy the module to remote machines before hand
- No shared folders or re-creating the module dynamically:
Example usage:
$s = New-PSSession MyTargetMachine
Get-Module MyLocalModule | Import-LocalModuleToRemoteSession -Session $s -Force
# Show module is loaded
Invoke-Command $s -ScriptBlock { Get-Module }
Import-LocalModuleToRemoteSession function
Note it doesn't load the module dependencies
<#
.SYNOPSIS
Imports a loaded local module into a remote session
.DESCRIPTION
This script copies a module's files loaded on the local machine to a remote session's temporary folder and imports it, before removing the temporary files.
It does not require any shared folders to be exposed as it uses the default Copy-To -ToSession paramter (added in PS 5.0).
#>
function Import-LocalModuleToRemoteSession
{
[CmdletBinding()]
param(
# Module to import
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName,Mandatory)]
[System.Management.Automation.PSModuleInfo]$ModuleInfo,
# PSSession to import module to
[Parameter(Mandatory)]
[System.Management.Automation.Runspaces.PSSession]
$Session,
# Override temporary folder location for module to be copied to on remote machine
[string]
$SessionModuleFolder=$null,
[switch]
$Force,
[switch]
$SkipDeleteModuleAfterImport
)
begin{
function New-TemporaryDirectory {
$parent = [System.IO.Path]::GetTempPath()
[string] $name = [System.Guid]::NewGuid()
New-Item -ItemType Directory -Path (Join-Path $parent $name)
}
}
process{
if( [string]::IsNullOrWhiteSpace($SessionModuleFolder) ){
Write-Verbose "Creating temporary module folder"
$item = Invoke-Command -Session $Session -ScriptBlock ${function:New-TemporaryDirectory} -ErrorAction Stop
$SessionModuleFolder = $item.FullName
Write-Verbose "Created temporary folder $SessionModuleFolder"
}
$directory = (Join-Path -Path $SessionModuleFolder -ChildPath $ModuleInfo.Name)
Write-Verbose "Copying module $($ModuleInfo.Name) to remote folder: $directory"
Copy-Item `
-ToSession $Session `
-Recurse `
-Path $ModuleInfo.ModuleBase `
-Destination $directory
Write-Verbose "Importing module on remote session @ $directory "
try{
Invoke-Command -Session $Session -ErrorAction Stop -ScriptBlock `
{
Get-ChildItem (Join-Path -Path ${Using:directory} -ChildPath "*.psd1") `
| ForEach-Object{
Write-Debug "Importing module $_"
Import-Module -Name $_ #-Force:${Using:Force}
}
if( -not ${Using:SkipDeleteModuleAfterImport} ){
Write-Debug "Deleting temporary module files: $(${Using:directory})"
Remove-Item -Force -Recurse ${Using:directory}
}
}
}
catch
{
Write-Error "Failed to import module on $Session with error: $_"
}
}
}