Usage of PSSession in Powershell + Remote, Import, Export

Table of Contents
. What is PSSession
. Enter-PSSession Cmdlet
. Exit-PSSession Cmdlet and some Enter-PSSession Tips
. New-PSSession Cmdlet
. Get-PSSession Cmdlet
. Remove-PSSession Cmdlet
. Export-PSSession Cmdlet
. Import the module you exported
. Import-PSSession Cmdlet

What is PSSession

PSSession (PowerShell Session) is used mostly to connect to remote computer. PowerShell establishes a persistent connection to run multiple commands with shared variables. These can be run with Invoke-Command. You can check our guide about Invoke-Command. PSSession runs in a background, so if any user is using that computer – he won’t notice your connection.

Enter-PSSession Cmdlet

The first cmdlet that is related to PSSession that we’re going to talk about is “Enter-PSSession“. It is equivalent to PSExec from SysInternals Suite.
The command starts an interactive session with single remote computer. It means that all the Cmdlets that you run, will be executed as if you were running them on remote computer’s Powershell directly. As of Powershell 6.0 you can use this command to connect with the session using Secure Shell (SSH).

To enter PSSession on “localhost”:

Enter-PSSession

This is without adding anything after the command.

To enter PSSession on remote computer:

$Computer = "KitchenComputer001"
$Credential = Get-Credential
Enter-PSSession –ComputerName $Computer –Credential $Credential

When using remoting with large scripts, it is better to define variables at the beginning of the script. In organizational environment you will be asked by Powershell to provide permissions for remoting, so a Credential will be required.

If you will run

Get-Process

It will show you all the processes that are currently running on “KitchenComputer001” computer.

You can create a connection using a specified port:

Enter-PSSession –ComputerName $Computer –Port 90 –Credential $Credential

Exit-PSSession Cmdlet and some Enter-PSSession Tips

To exit the session “Exit-PSSession” cmdlet is used:

Exit-PSSession

Alias of “Exit” can also be used, but general recommendation is not to use aliases in powershell.

Enter-PSSession doesn’t work well with IP addresses. If you get an error you may add an exception to the Trusted Hosts of the remote computer (“*” adds all computers, so beware):

Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force

New-PSSession Cmdlet

Another usage of PSSession – as an object with “New-PSSession“:

$RemoteComputer = "KitchenComputer001"
$Credential = Get-Credential
$RemoteSession = New-PSSession –ComputerName $RemoteComputer -Credential $Credential

Then after defining an object, you can use it with “Invoke-Command

Invoke-Command –Session $RemoteSession –ScriptBlock {
    Get-Host
}

While using “New-PSSession” with FQDN name (like: KitchenComputer001.subdomain.domain.com) you might get an error:

WinRM cannot process the request. The following error occurred while using Kerberos authentication

Try using NetBIOS names (Non-FQDN). Like: KitchenComputer001.

In addition, with “New-PSSession” you can connect to several computers at once:

New-PSSession –ComputerName Kitchen001,Kitchen002,Kitchen003 -Credential $Credential

The same way you can also define separate variables for each session:

$Session1, $Session2, $Session3 = New-PSSession –ComputerName Kitchen001,Kitchen002,Kitchen003 -Credential $Credential

On the Cmdlet page it states that the assignment operator “=” assigns variables respectively, like $Session1 will Receive “Kitchen001” session, $Session2 will be “Kitchen002” session, etc. But in our environment it wasn’t the case. For some reason it was $Session1 got “Kitchen002”, $Session2 got “Kitchen003” and $Session3 got “Kitchen001”. Take notice, if in your environment it works fine, you may run it on another computer and you might get different results. The problem is probably with the assignment operator on multiple variables.

Connection with port and SSL:

New-PSSession -ComputerName Server01 -Port 8081 –UseSSL

Connecting with IIS of a server, like Exchange:

$ExchangeSession = New-PSSession -ConnectionUri "http://exchange.domain.com/powershell/" -ConfigurationName Microsoft.Exchange -Authentication Kerberos

If you want to use the configuration of a specific service you need to state that in a “-ConfigurationName” preference. Here is an example of using “Microsoft.Exchange”. If the “ConfigurationName” preference is not set, “Microsoft.PowerShell” is used by default.
In this example specific “-Authentication” property forced to Kerberos.

Another cool feature is setting a timeout for a session, so you won’t need to close it manually or with another Cmdlets. You will need to use an object from “New-PSSessoinOption” Cmdlet with “-IdleTimeout” preference (set in milliseconds):

$SessionOption = New-PSSessionOption -IdleTimeout 60000
New-PSSession –ComputerName KitchenComputer001 –SessionOption $SessionOption

This session will close after a minute.

Get-PSSession Cmdlet

To find out to which computers you’re connected right now we’ll use “Get-PSSession“:

Get-PSSession

Then you can find opened sessions that you have to particular computer:

Get-PSSession -ComputerName "Kitchen001"

You can insert PSSession as an object into variable (it will be the same object as with New-PSSession):

$Session = Get-PSSession -Id 2

You can now execute commands on this session variable with “Invoke-Command” as we did in “New-PSSession” example above.
If you connected to 3 sessions, you can save them to separate variables:

New-PSSession -ComputerName Kitchen001, Kitchen002, Kitchen003 -Credential $Credential
$Session1, $Session2, $Session3 = Get-PSSession

For some it can be easier to use sessions as dedicated variables.
Or you can input all the sessions into Array:

$Sessions = Get-PSSession

Remove-PSSession Cmdlet

After you connected a few sessions, eventually you will need to close some. “Remove-PSSession” will help you with that:

Remove-PSSession -ComputerName Kitchen002

You can close couple of sessions:

Remove-PSSession –Id 1, 2

The easiest way to remove all the sessions:

Get-PSSession | Remove-PSSession

Or:

Remove-PSSession -Session (Get-PSSession)

Export-PSSession Cmdlet

This is useful if you have some Powershell module on remote computer that you want to use its cmdlets locally (while you don’t have that Powershell module locally). 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 exports cmdlets, functions, aliases and other command types.

You may import the module later on another computer and cmdlet execution will take place in original or similar remote session. For example if you exported session with computer “KitchenAD001” and the user that was connected is “User01” with password “ComplicatedPassword00”, when you import the module on another computer, the cmdlets that you exported will be physically run on the “KitchenAD001” with credential of “User01”, you only will be asked for a password.

$Computer = KitchenAD001
$Credential = Get-Credential
$PSSessionForCommands = New-PSSession $Computer -Credential $Credential
Invoke-Command -Session $PSSessionForCommands -ScriptBlock { Import-Module ActiveDirectory }

# You must import the module which doesn't come in default session
Export-PSSession -Session $PSSessionForCommands -CommandName *-AD* -OutputModule ActiveDirectoryRemote –AllowClobber -Force

“-CommandName *-AD*” takes into consideration all the Cmdlets that have “-AD” in their name (Get-ADForest, Get-ADOrganizationalUnit, Get-ADGroupMember, etc.).
“-OutputModule ActiveDirectoryRemote” outputs to the module named “ActiveDirectoryRemote”, which by default placed in

$home\Documents\WindowsPowerShell\Modules\ActiveDirectoryRemote

The last folder is the name of the module that you provided.
“-AllowClobber” Exports the specified commands, even if they have the same names as commands in the current session. This is not the behavior by default. If there are similar commands in the local session with the commands available on the remote computer, the commands from the remote computer will be omitted. “AllowClobber” does the opposite, local commands will be exchanged with the remote commands.
“-Force” overwrites the module if it exists.
If you want to be more specific about the Cmdlets, you can export all the Cmdlets that contain “Get-” and “Set-” in the name:

Export-PSSession -Session $PSSessionForCommands -CommandName Get-*, Set-* -OutputModule ActiveDirectoryRemote –AllowClobber –Force

Also, you can specify exact location for the module:

Export-PSSession -Session $PSSessionForCommands -CommandName Get-*, Set-* -OutputModule ("C:\Scripts\ActiveDirectoryRemote") –AllowClobber –Force

Import the module you exported

To import the module with all the active directory Cmdlets that you exported:

Import-Module ActiveDirectoryRemote –Global

And if you used specific location:

Import-Module ("C:\Scripts\ActiveDirectoryRemote\ActiveDirectoryRemote.psd1") –Global

If the module was exported with “AllowClobber” property and you want to avoid local Cmdlets got exchanged with the remote ones, you can disable clobbing on import with “Prefix” property:

Import-Module ActiveDirectoryRemote -Prefix Remote

When you imported the module, the connection wasn’t still made to the remote session, but you already can see that these cmdlets were added to your session with:

Get-Command

Only after you execute one of the remote commands, the connection will be made and you will be prompted for password.

Import-PSSession Cmdlet

Last one is “Import-PSSession“. Works with almost the same properties as “Export-PSSession”, but without saving a file and importing. Basically “Import-PSSession” is “Export-PSSession” and “Import-Module” combined.

# Make a connection
$ExchangePsSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://exchanges.server.domain.com" -Authentication Kerberos
# Import this session into your cmdlet list
Import-PSSession $ExPsSession
# Use the Cmdlets from this session
Get-Mailbox -Identity User

Here’s another usage with “AllowClobber” property with “Get-” and “Set-” commands:

Import-PSSession -Session $PSSessionForCommands -CommandName Get-*, Set-* –AllowClobber

Another feature is to import whole module:

$Computer = KitchenAD001
$Credential = Get-Credential
$PSSessionForCommands = New-PSSession $Computer -Credential $Credential
Invoke-Command -Session $PSSessionForCommands { Import-Module ActiveDirectory }
Import-PSSession -Session $PSSessionForCommands -Module ActiveDirectory

You have to invoke “Module import” on remote session to add the Cmdlets to the session or else it won’t work. Only then import them with the appropriate Cmdlet.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.