如何妥善处置执行PowerShell远程会话操作后遗留的远程连接?
Hey there, let's work through those lingering PowerShell remote sessions you're facing. I've dealt with this exact issue before, so here are practical, reliable steps to clean them up and prevent future occurrences:
第一步:先确认遗留会话的状态
First, let's get clarity on which sessions are still hanging around. Run this command to list all active/disconnected sessions, filtered to your target VM:
Get-PSSession -ComputerName $VM
This will show you details like SessionId, State, and ComputerName—critical info for targeted cleanup.
直接清理遗留会话的方法
1. 批量清理目标VM的所有会话
If you want to wipe all sessions tied to that VM (safe if you know no other active processes are using them), pipe the results to Remove-PSSession:
Get-PSSession -ComputerName $VM | Remove-PSSession
2. 强制清理顽固/断开的会话
Sometimes sessions get stuck in a Disconnected state and won't delete normally. Add the -Force parameter to force removal:
Get-PSSession -ComputerName $VM -State Disconnected | Remove-PSSession -Force
You can also use this to clear all sessions for the VM with force:
Get-PSSession -ComputerName $VM | Remove-PSSession -Force
3. 远程端手动清理(极端情况)
If local commands don't work, log into the target VM directly and run these commands to clean up sessions from the remote side:
# List all sessions on the VM Get-PSSession # Remove specific sessions by ID Remove-PSSession -Id <SessionId> # Or wipe all sessions Get-PSSession | Remove-PSSession -Force
As a last resort, you can restart the WinRM service (note: this will terminate all active remote sessions on the VM):
Restart-Service WinRM -Force
预防会话遗留的最佳实践
The root cause here is likely that your original script didn't account for errors—if a command failed mid-execution (like the New-PSDrive step), the script might skip the Remove-PSSession line. Fix this with a try/finally block to guarantee session cleanup, no matter what:
try { $session = New-PSSession -ComputerName $VM -Credential $CurrentUser # Execute your remote commands here Invoke-Command -Session $session -ScriptBlock { $drive = New-PSDrive -Credential $Using:CurrentUser "dummyDriveName" -Root (Split-Path $Using:TargetPath) -PSProvider "FileSystem" Set-Location $Using:TargetPath } Invoke-Command -Session $session -ScriptBlock { Remove-PSDrive "dummyDriveName" } } finally { # This block runs ALWAYS, even if an error occurs if ($null -ne $session) { Remove-PSSession -Session $session -Force } }
You can also set an idle timeout when creating the session to auto-expire inactive sessions:
$session = New-PSSession -ComputerName $VM -Credential $CurrentUser -IdleTimeoutSec 300 # Auto-disconnect after 5 minutes of inactivity
内容的提问来源于stack exchange,提问作者Brondahl

