Skip to content

Instantly share code, notes, and snippets.

@steviecoaster
Last active November 28, 2024 14:58
Show Gist options
  • Save steviecoaster/2229e9351fb329a6c79154d6f5017421 to your computer and use it in GitHub Desktop.
Save steviecoaster/2229e9351fb329a6c79154d6f5017421 to your computer and use it in GitHub Desktop.
Use a module from another machine with Implicit remoting

Implicit Remoting explained

Implicit remoting allows you to load a module from a remote session and execute it "locally". What you are actually doing is running a proxy command. The actual function executes on the remote session, and the data is returned to you locally.

This approach does have the same caveats as running a command directly via Invoke-Command in that it is deserialized and rehydrated, losing any available methods on the object.

This is still a hugely useful trick, and I highly recommend using a prefix so you know in your code when something is running on the remote system. For example Get-ADComputer may become Get-RemoteADComputer. You can specify whatever prefix you want, just make it helpful to future you and other members of your team who may have to support the code later.

Here's an older blog post with some more good info and explaination: https://devblogs.microsoft.com/scripting/remoting-the-implicit-way/

Function New-ImplicitSession {
<#
.SYNOPSIS
Create a new Implicit remoting session
.DESCRIPTION
Access remote modules by implicityly importing them into your current powershell session
.PARAMETER Computername
The computername which has the module you wish to use installed
.PARAMETER Module
The name of the module to import
.PARAMETER Prefix
If desired, you may prefix the imported module's commands with a descriptor
.EXAMPLE
New-ImplicitSession -Computername DC01 -Module ActiveDirectory
.EXAMPLE
New-ImplicitSession -Computername Fileserver -Module NTFSSecurity -Prefix Remote
#>
[cmdletBinding()]
Param(
[Parameter(Mandatory,Position=0)]
[Alias('Name')]
[String]
$Computername,
[Parameter(Mandatory,Position=1)]
[String]
$Module,
[Parameter(Position=2)]
[String]
$Prefix
)
Begin {}
Process {
$Session = New-PSSession -ComputerName $Computername
$SessionInfo = @{
Target = $Computername
}
Invoke-Command -Session $Session -ArgumentList $Module -ScriptBlock {
Param($Param)
Import-Module $Param
}
If($Prefix){
Import-PSSession -Prefix $Prefix -Session $Session -ErrorAction SilentlyContinue -WarningAction SilentlyContinue >$null
$SessionInfo.Add('Prefix',$Prefix)
}
Else{
Import-PSSession -Session $Session -ErrorAction SilentlyContinue -WarningAction SilentlyContinue >$null
}
$SessionInfo.Add("Id",$Session.Id)
$SessionInfo.Add("State",$Session.State)
$SessionInfo.Add("LoadedModule",$Module)
return [pscustomobject]$SessionInfo
Write-Warning -Message "Remember to run Get-PSSession | Remove-PSSession when finished!"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment