Scenario: You want to disconnect all remote sessions on ServerComputers via PowerShell remotely.
Script:
#Disconnect Terminal Sessions via PowerShell################
#Gather the Servers in the $Servers Variable
$Servers = get-exchangeserver Exch* | Select -expandproperty Name
#Gather the Sessions
$TS = $Servers | %{
$computer = $_
quser /server:$computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {
$CurrentLine = $_.Trim() -Replace ‘s+’,’ ‘ -Split ‘s’
$HashProps = @{
UserName = $CurrentLine[0]
ComputerName = $Computer
}
# If session is disconnected different fields will be selected
if ($CurrentLine[2] -eq ‘Disc’) {
$HashProps.SessionName = $null
$HashProps.Id = $CurrentLine[1]
$HashProps.State = $CurrentLine[2]
$HashProps.IdleTime = $CurrentLine[3]
$HashProps.LogonTime = $CurrentLine[4..6] -join ‘ ‘
$HashProps.LogonTime = $CurrentLine[4..($CurrentLine.GetUpperBound(0))] -join ‘ ‘
} else {
$HashProps.SessionName = $CurrentLine[1]
$HashProps.Id = $CurrentLine[2]
$HashProps.State = $CurrentLine[3]
$HashProps.IdleTime = $CurrentLine[4]
$HashProps.LogonTime = $CurrentLine[5..($CurrentLine.GetUpperBound(0))] -join ‘ ‘
}
New-Object -TypeName PSCustomObject -Property $HashProps | Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
}
}
#Disconnect the Sessions
$TS | %{
$id = $_.id
$Name = $_.computerName
$User = $_.Username
rwinsta $ID /server:$name
Write-Host “Session $Id for $User on $Name successfully disconnected”
}
#######################################################