PowerShell | Log Off Users
<#
Summary:
Query remote computer by name
List results of logged on users
Option to continue Y/N
If yes asks for ID for account to Logoff
Logs off requested account
Author: Scott Head
Date: 02/09/2022
Version: 1.0
#>
CLS
#Clear Variable
$UserID=""
$ComputerName=""
$ERRORS =""
$UserEntry=""
$ERROR2 =""
#Get Input From User
write-Host "`n"
$ComputerName = Read-Host "Enter Computer Name"
#Error Trap
If($ComputerName -eq ""){
CLS
Write-Host "`n"
Write-Host "No ComputerName Entered"
Write-Host "Session Ended"
Pause
Break
}
#Query Computer for Logged on Users
Try{
Invoke-Command -ComputerName $ComputerName -ScriptBlock {Query User /Server:$ComputerName} -ErrorVariable ERRORS -ErrorAction SilentlyContinue
}Catch{
}
#Error Trap
If($ERRORS -like "No User exists for *"){
CLS
Write-Host "`n"
Write-Host "No Users Found Logged in to $ComputerName"
Write-Host "Session Ended"
pause
Break
}
#Error Trap
If($ERRORS -like "*failed with the following error message*"){
CLS
Write-Host "`n"
Write-Host "Could Not Connect o $ComputerName"
Write-Host "Session Ended"
pause
Break
}
#Option to Display to user
write-Host "`n"
$UserEntry=Read-Host "Do you need to remove a user? (Y/N)"
write-Host "`n"
#Response From User Conditional
If(($UserEntry -eq "y") -or ($UserEntry -eq "Y")){
#Reuest User ID
$UserID=""
$UserID = Read-Host "Enter User ID Number from computer $Computername"
#Error Trap
if($UserID -ne ""){
#Disconnects User Session
Try{
Invoke-Command -ComputerName $ComputerName -ScriptBlock {LogOff $Args} -ArgumentList $UserID -ErrorVariable ERROR2 -ErrorAction SilentlyContinue
}Catch{
}
#Error Trap
if($ERROR2 -ne ""){
CLS
Write-host " ---ERRROR--- `n Account Removal `n No Changes Were Made `n $ERROR2"
pause
Break
}
}Else{
CLS
write-host "No ID Entered"
Write-host "Session Ended"
write-Host "`n"
}
}Else{
CLS
Write-host "Session Ended"
write-Host "`n"
}