A best practice for automatically cleaning up PSSessions
suggest changeWhen a remote session is created via the New-PSSession cmdlet, the PSSession persists until the current PowerShell session ends. By default, the PSSession and all associated resources continue to be used until the current PowerShell session ends.
Multiple active PSSessions can become a strain on resources, particularly for long-running or interlinked scripts that create hundreds of PSSessions in a single PowerShell session.
It is best practice to explicitly remove each PSSession after it is finished being used. [1]
The following code template utilises try-catch-finally in order to achieve the above, combining error handling with a secure way to ensure all created PSSessions are removed when they are finished being used:
try
{
$session = New-PSSession -ComputerName "RemoteMachineName"
Invoke-Command -Session $session -ScriptBlock {write-host "This is running on $ENV:ComputerName"}
}
catch
{
Write-Output "ERROR: $_"
}
finally
{
if ($session)
{
Remove-PSSession $session
}
}
References: [1] https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/new-pssession