Created
May 10, 2018 09:21
-
-
Save Sarafian/83426d8cc6dd52635065d54867b936ba to your computer and use it in GitHub Desktop.
Disconnect/Terminate remote sessions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.Synopsis | |
Disconnects your user from remote computers | |
.DESCRIPTION | |
This scripts uses the quser and qwinsta to scan for session on a remote computer and then rwinsta to disconnect it | |
.NOTES | |
.LINK | |
https://sarafian.github.io/ | |
.PARAMETER ComputerName | |
The string or array of string for which a query will be executed | |
.EXAMPLE | |
.\Disconnect-RemoteSessions.ps1 -ComputerName @("server01","server02") | |
#> | |
param( | |
[Parameter(Mandatory=$true)] | |
[ValidateCount(1,[System.Int32]::MaxValue)] | |
[string[]]$ComputerName | |
) | |
$currentErrorPreference=$ErrorActionPreference | |
try | |
{ | |
$ErrorActionPreference='SilentlyContinue' | |
Write-Host "Scanning remote sessions for user $($env:USERNAME) on $computers" | |
$sessions= $ComputerName | ForEach-Object { | |
$computerName=$_ | |
#Execute qwinsta | |
$items=qwinsta $env:USERNAME /server:$computerName |Select-Object -Skip 1 |ForEach-Object { $_.Trim() -Replace '\s+',' ' -Split '\s' } | |
if($items) | |
{ | |
$newSession = New-Object System.Object | |
$newSession | Add-Member -type NoteProperty -name User -value $items[1] | |
$newSession | Add-Member -type NoteProperty -name ComputerName -value $computerName | |
$newSession | Add-Member -type NoteProperty -name ID -value $items[0] | |
$newSession | |
} | |
# Execute quser | |
$items=quser $env:USERNAME /server:$computerName |Select-Object -Skip 1 |ForEach-Object { $_.Trim() -Replace '\s+',' ' -Split '\s' } | |
if($items) | |
{ | |
$newSession = New-Object System.Object | |
$newSession | Add-Member -type NoteProperty -name User -value $items[0] | |
$newSession | Add-Member -type NoteProperty -name ComputerName -value $computerName | |
$newSession | Add-Member -type NoteProperty -name ID -value $items[1] | |
$newSession | |
} | |
} | |
if($sessions) | |
{ | |
Write-Host "Found remote sessions for user $($env:USERNAME) on $computers" | |
$sessions|ForEach-Object { | |
$id=$_.ID | |
$computerName=$_.ComputerName | |
Write-Debug "rwinsta $id /server:$computerName" | |
Write-Verbose "Disconnecting session $id on $computerName" | |
rwinsta $id /server:$computerName | |
Write-Host "Disconnected session $id on $computerName" | |
} | |
} | |
else | |
{ | |
Write-Host "Could not find remote sessions for user $($env:USERNAME) on $computers" | |
} | |
} | |
finally | |
{ | |
$ErrorActionPreference=$currentErrorPreference | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment