Blog Archives
Managing Remote (WSMAN) sessions with PowerShell
There was a post on the forums asking about how to remove a session if the max sessions (5) had been reached. You could use Get-Process to find and kill a WsmProvHost but killing things is never a good idea. There is a Get-WSManInstance but it’s not very friendly so I’ve wrapped that and Remove-WSManInstance in to two functions that are much more user-friendly. Just copy and past this in to a file and you can use Import-Modulein your profile to add these functions in to your environment.
<#
.Synopsis
Display WSMan Connection Info
.DESCRIPTION
This is a wrapper to Get-WSManInstance
.EXAMPLE
Get-RemotePSSession ServerABC
.EXAMPLE
$s = Get-RemotePSSession ServerABC
$s | Remove-RemotePSSession
#>
function Get-RemotePSSession
{
[CmdletBinding()]
Param
(
# Computer to query.
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[string]
$ComputerName,
# use SSL
[switch]
$UseSSL
)
Begin
{
try{
Add-Type @"
namespace JRICH{
public class PSSessionInfo
{
public string Owner;
public string ClientIP;
public string SessionTime;
public string IdleTime;
public string ShellID;
public string ConnectionURI;
public bool UseSSL=false;
}}
"@
}
catch{}
$results = @()
}
Process
{
$port = if($usessl){5986}else{5985}
$URI = "http://$($computername):$port/wsman"
$sessions = Get-WSManInstance -ConnectionURI $URI shell -Enumerate
foreach($session in $sessions)
{
$obj = New-Object jrich.pssessioninfo
$obj.owner = $session.owner
$obj.clientip = $session.clientIp
$obj.sessiontime = [System.Xml.XmlConvert]::ToTimeSpan($session.shellRunTime).tostring()
$obj.idletime = [System.Xml.XmlConvert]::ToTimeSpan($session.shellInactivity).tostring()
$obj.shellid = $session.shellid
$obj.connectionuri = $uri
$obj.UseSSL = $usessl
$results += $obj
}
}
End
{
$results
}
}
<#
.Synopsis
Logoff remote WSMAN session
.DESCRIPTION
This function will take a JRICH.PSSessionInfo object and disconnect it
.EXAMPLE
$s = Get-RemotePSSession ServerABC
$s | Remove-RemotePSSession
#>
function Remove-RemotePSSession
{
[CmdletBinding()]
Param
(
# Session to be removed.
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[jrich.pssessioninfo[]]
$Session
)
Process
{
foreach($connection in $session)
{
Remove-WSManInstance -ConnectionURI $connection.connectionuri shell @{ShellID=$connection.shellid}
}
}
}
Edit: Thanks Alex for catching the use of “CredSSP” vs “UseSSL” which is the common arg on PSSession cmdlets!
