Remove, Save and Restore - Remote PowerShell Sessions in SharePoint 2010
I have been working with Remote Powershell and it is amazing to use this. Just imagine I dont need SharePoint server on my box just powershell on my box and normal Powershell scripting knowledge. A typical pain can be to create a new session everytime you close the PS.exe and set up all the parameters. Voila, there is a solution for the same. PowerShell exposes two methods – Import-PSSession and Export-PSSession.
Saving Remote Session
Rather than working with sessions created by Import-PSSession which are temporary in nature, one can save a session. As specified above one can achieve the same with the Export-PSSession cmdlet.
Example:
PS> $Session= New-PSSession -ComputerName “ServerName” -Credential DomainName\UserName
PS Export-PSSession -Session $session -CommandName *-spsite -OutputModule MyRemoteCommands -AllowClobber –force
Restore Remote Session
After implicit remoting module is saved, one can invoke the remote commands without having to ever again use New-PSSession, Invoke-Command, Import-PSSession or Export-PSSession. Let's see how that works:
PS> Import-Module MyRemoteCommands -Prefix Remote
Let's try to invoke one of the commands:
PS C:\Windows\system32> $site = Get-RemoteSPSite(" https://siteurl") Creating a new session for implicit remoting of "Get-SPSite" command...
Remove Remote Session
If requirement is just to close the connection and remove temporary files, use the following command:
Remove-PSSession $NameOfSessionInstance