Powershell: Pull Cmdlets/Modules from remote server
Sometimes you need certain cmdlets/modules installed to use with your PowerShell script, unfortunately you are unable to install the SDK/Console or you don’t wish to keep updating it on multiple locations. Using PowerShell PSSession to connect to a remote computer that already has the cmdlets and pull them into your session is a great alternative way to centralize the cmdlets in one location and never have to install anything. This guide will show you how to connect and pull in the cmdlets into your session without having to use invoke-command for every command. You can force TLS 1.2 in your script in case it is required, you can follow my guide here.
First we need to create a session variable and a server variable
1 2 | $server = "potatoserver" $s = New-PSSession -ComputerName $server |
Now we can import the module into our session
1 | Invoke-Command -Command {Get-Module -ListAvailable MyModule* | Import-Module} -Session $s |
or
1 | Invoke-Command -Command {Import-Module MyModule} -Session $s |
Next we import the session (Optional: if you have some issues you may need to do the following)
1 | Import-PSSession -Session $s -Module MyModule |
You should now be able to run your PowerShell script, it should connect to the remote computer and import the module(s). Here you can write your code naively without using the invoke-command
To close the session at the end of your script you must use Remove-PSSsesion
1 | Remove-PSSession -ID $s.ID |
Here is the full example
1 2 3 4 5 6 7 8 | $server = "potatoserver" $s = New-PSSession -ComputerName $server Invoke-Command -Command {Get-Module -ListAvailable MyModule* | Import-Module} -Session $s # Some Code Remove-PSSession -ID $s.ID |