PowerShell script to logoff user remotely on a list of servers

/ November 25th, 2015/ Posted in PowerShell, Server, Windows / No Comments »

Problem:

I needed a PowerShell script to remotely logoff a domain user on multiple servers.

 

Solution:

Using my script with the PowerShell module PSTerminalServices from https://psterminalservices.codeplex.com/
I was able to create a method to disconnect the users remotely

$username = 'jbaldanza'
$filepath = 'c:\temp\servers.txt'

If (!(Get-module PSTerminalServices )) 
{
    try 
    {
        Import-Module PSTerminalServices
        Write-Host "PSTerminalServices Module Loaded" -ForegroundColor Green
    } 
    catch 
    {
        Write-Host "PSTerminalServices module does not exist, please install" -ForegroundColor Red
    }
}

foreach ($server in (Get-Content -Path $filepath)) 
{
    Write-Host "Checking for $username on $server" -ForegroundColor Cyan   
    try 
    {
        $loggedInUsers = get-tssession -ComputerName $server
        if ($loggedInUsers.UserName -contains $username) 
        {

            Write-Host "Found $username connected to $server" -ForegroundColor Green
            $userNameSessionID = $loggedInUsers | Where-Object -Property UserName -eq $username | Select-Object -Property SessionID
            foreach ($sessionID in $userNameSessionID) 
            {
                $currentSessionID = $sessionID.SessionId       
                Write-Host "$username's SessionID is $currentSessionID" -ForegroundColor Cyan
                try 
                {
                    Start-Sleep 2
                    Stop-TSSession -ComputerName $server -Id $currentSessionID -Confirm:$false -Force
                    Write-Host "Disconnected $username's session $currentSessionID from $server" -ForegroundColor Green
                }
                catch 
                {
                    Write-Host "Unable to disconnect $username's session $currentSesionID from $server" -ForegroundColor Red
                }
            }
        }
        else 
        {
            Write-Host "User $username not connected to $server" -ForegroundColor Yellow
        }
    }
    catch 
    {
        Write-Host "Unable to connect to $server" -ForegroundColor Red
    }
}

Leave a Reply

Name required

Please Submit Answer * Time limit is exhausted. Please reload CAPTCHA.