Created
April 3, 2019 10:52
-
-
Save spaghettidba/a0a597f3da8b6bba0a4f079c6ec11abe to your computer and use it in GitHub Desktop.
Disconnect-RemoteSession #blog
This file contains 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
[CmdletBinding()] | |
Param( | |
[Parameter(Mandatory=$False,Position=1)] | |
[string[]]$servers | |
) | |
if(-not $servers){ | |
$servers = Get-Content servers.txt | |
} | |
$servers | ForEach-Object { | |
$serverName = $_ | |
$out = qwinsta /server $serverName 2>&1 | |
if($LASTEXITCODE -ne 0) { | |
continue | |
} | |
$sessions = $out | ?{ $_ -notmatch '^ SESSIONNAME' } | %{ | |
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device" | |
$item.Active = $_.Substring(0,1) -match '>' | |
$item.SessionName = $_.Substring(1,18).Trim() | |
$item.Username = $_.Substring(19,20).Trim() | |
$item.Id = $_.Substring(39,9).Trim() | |
$item.State = $_.Substring(48,8).Trim() | |
$item.Type = $_.Substring(56,12).Trim() | |
$item.Device = $_.Substring(68).Trim() | |
$item | |
} | |
foreach ($session in $sessions){ | |
if ($session.Username -ne "" -or $session.Username.Length -gt 1){ | |
if($session.Username -ceq $env:USERNAME){ | |
Write-Output "Logging off $($session.Username) from $serverName" | |
logoff /server $serverName $session.Id | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment