How to close orphaned PowerShell sessions?
The remote jobs would run under a wsmprovhost.exe process per job. You should be able to brute force terminate these processes with WMI - or even remotely reboot the machine. You run the risk of killing hosted jobs for other users/activities, of course.
This would terminate all wsmprovhost.exe processes on the computer named (or array of computer names):
(gwmi win32_process -ComputerName $RemoteServer) |?
{ $_.Name -imatch "wsmprovhost.exe" } |%
{ $_.Name; $_.Terminate() }
I know this post is kinda old. @Matthew Wetmore has a great solution to remove ALL PSSessions from a remote server. But, @SuHwak had a follow on question, of how to stop only sessions that a specific user has spawned.
To that end, I wrote a function to assist.
function Get-PSSessionsForUser
{
param(
[string]$ServerName,
[string]$UserName
)
begin {
if(($UserName -eq $null) -or ($UserName -eq ""))
{ $UserName = [Environment]::UserName }
if(($ServerName -eq $null) -or ($ServerName -eq ""))
{ $ServerName = [Environment]::MachineName }
}
process {
Get-CimInstance -ClassName Win32_Process -ComputerName $ServerName | Where-Object {
$_.Name -imatch "wsmprovhost.exe"
} | Where-Object {
$UserName -eq (Invoke-CimMethod -InputObject $_ -MethodName GetOwner).User
}
}
}
And, to use it....
#Get, but do not terminate sessions for the current user, on the local computer.
Get-PSSessionsForUser
#Terminate all sessions for for the current user, on the local computer.
(Get-PSSessionsForUser) | Invoke-CimMethod -MethodName Terminate
<####################################>
#Get, but do not terminate sessions for a specific user, on the local computer.
Get-PSSessionsForUser -UserName "custom_username"
#Terminate all sessions for a specific user, on the local computer.
(Get-PSSessionsForUser -UserName "custom_username") | Invoke-CimMethod -MethodName Terminate
<####################################>
#Get, but do not terminate sessions for the current user, on a remote server.
Get-PSSessionsForUser -ServerName "remote_server"
#Terminate all sessions for the current user, on a remote server.
(Get-PSSessionsForUser -ServerName "remote_server") | Invoke-CimMethod -MethodName Terminate
<####################################>
#Get, but do not terminate sessions for a specific user, on a remote server.
Get-PSSessionsForUser -UserName "custom_username" -ServerName "remote_server"
#Terminate all sessions for a specific user, on a remote server.
(Get-PSSessionsForUser -UserName "custom_username" -ServerName "remote_server") | Invoke-CimMethod -MethodName Terminate