Logoff a user from multiple servers with powershell

Logoff a user from multiple servers with powershell

This article is related to the article I recently wrote on how to identify what servers a user is logged on to with powershell. Actually we can re-use all of that script and just implement the logoff to it. We have a couple of ways to logoff a user from multiple server with pwoershell, based on the script located in the article I posted above:

  1. Utilise the .csv file, from the previous script, in a new script and run through it.
  2. Modify the script to add the log off functionality.

Both Options are really simple to follow and are both helpful since the first one will allow you to have a quick look through the list whilst the second one can be used when you’re sure you want to log everybody off!

1 – Utilise the .csv file, from the previous script, in a new script and run through it.

Remember that the script returned a .csv file composed of two columns per row: the hostname and the session ID of the user we want to log off. Since the previous script has done all of the work, all we need to do will be:

#Get the content from the CSV file with import-csv
$csvContent = Import-CSV "c:\whereisloggedon.csv"
	# $csvContent.Hostname will report all hostnames and .SessionID all Session IDs

#Go through each item in $csvContent
Write-Host "Currently logging off from:"
$csvContent | %{
	Write-Host "$($_.Hostname)"
	#Log off user from server based on server ID
	logoff $_.SessionID /server:$_.Hostname
}

 

Easy! Pay attention though! If this is not your own account you’re working with, I would suggest you to add an extra check to make sure you’re logging off the right username. You could do something like this (we’re ignoring the Session ID the previous script caught):

#Get the content from the CSV file with import-csv
$csvContent = Import-CSV "c:\whereisloggedon.csv"
	# $csvContent.Hostname will report all hostnames and .SessionID all Session IDs

$username = "User.Name"

#Go through each item in $csvContent
Write-Host "Currently logging off from:"
$csvContent | %{

	#Grab the Session ID
	$sessionID = ((cmd /c quser /server:$_.Hostname "2>NUL"| ? { $_ -match $username }) -split ' +')[2]
	If ($sessionID -AND $sessionID -NotLike "*rdp*" -AND $sessionID -ne "console")
	{
		Write-Host "$($_.Hostname)"
		#Log off user from server based on server ID
		logoff $SessionID /server:$_.Hostname
	}
}

 

Note: with the second script, you can use any list to perform this. You do not need the session ID as the script will find it by itself!

2 – Modify the script to add the log off functionality.

This is exactly the same script of the above article, it just has an extra line that will log off the user as well.

#The username to check against each server
$Username = "User.Name"

#Output file
	$csvOutput = 'C:\whereisloggedon.csv'
		#Deletes the output file if it exists
			If (Test-Path $csvOutput){
				Remove-Item $csvOutput
			}
		#Add the first line to the CSV file
		Add-Content -Path $csvOutput -Value "Hostname,SessionID"

#Get all Servers' names in the Domain that are not enabled.
$serverList=(Get-ADComputer -Filter ('(OperatingSystem -Like "*SERVER*") -AND (Enabled -Eq "True")') | select-object Name).Name

#Start a foreach cycle which will go through each Server in the ServerList
foreach ($Server in $serverList)
	{
		#Ping the Server
		$ping = Test-Connection $Server -Count 1 -EA Silentlycontinue

		#If Ping is successfull then keep going
		if($ping)
		{
			#Get server session ID if $username is logged on - cmd /c is needed for the 2>NUL to avoid quser to write "No User exists for *" when nobody is logged on a server.
			$sessionID = ((cmd /c quser /server:$server "2>NUL"| ? { $_ -match $username }) -split ' +')[2]
			
			#If sessionsID exists, write it to console and to the output file but exclude any live RDP connection or console (ie: rdp-tcp#1)
				If ($sessionID -AND $sessionID -NotLike "*rdp*" -AND $sessionID -ne "console")
				{
					#Write to console
					Write-Host "$($Username) is logged on $($Server) with ID: $($sessionID). The script will attempt to logoff the user."
					#Log off the user
					logoff $SessionID /server:$Server
					#Write into $csvOutput
						Add-Content -Path $csvOutput -Value "$($Server),$($sessionID)"
				}
		}
	}

This is pretty much it on how to logoff a user from multiple servers with powershell.

If you haven’t read yet the article posted at the beginning of this post, I totally recommend you to do it so that you can better understand the script above.

IT Droplets

IT Droplets