69 lines
2.9 KiB
PowerShell
69 lines
2.9 KiB
PowerShell
Function Get-LogOffUser($ComputerName){
|
|
|
|
Try
|
|
{
|
|
$userName = (Get-CimInstance -Class win32_computersystem -ComputerName $ComputerName).UserName
|
|
|
|
if(!$userName)
|
|
{
|
|
$userName = "**None**"
|
|
Write-Host "No logged in user on $ComputerName" -ForegroundColor Green
|
|
return
|
|
|
|
|
|
}else{
|
|
|
|
Write-Host "You are about to remotely logoff [$userName] from this [$ComputerName]"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Catch
|
|
{
|
|
Write-Host "Could not connect to the target computer.`nCheck that the computer is powered on and the name is typed correctly." -ForegroundColor Yellow -BackgroundColor DarkCyan
|
|
|
|
}
|
|
|
|
#Displays the username for the current user, then prompts for a 'Yes' or 'No (Cancel)'
|
|
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes (Logoff $username)"
|
|
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No (Cancel)"
|
|
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
|
|
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
|
|
|
|
#If you select Yes, then the following switch (0) runs
|
|
#If you select No, then a message displays and the script will exit
|
|
|
|
Switch ($result)
|
|
{
|
|
|
|
0{
|
|
#If you've gotten this far, then $computerWMI should have connected successfully to the remote computer
|
|
#There is also a user logged in, and the correct user has been confirmed by pressing the 'Yes' button
|
|
#This portion of the switch connects to the Win32_OperatingSystem class, then issues a logoff command
|
|
Write-host "Attempting to logoff [$userName] from [$ComputerName]." -ForegroundColor Yellow
|
|
|
|
Try
|
|
{
|
|
(Get-WmiObject -Class win32_operatingsystem -ComputerName $ComputerName -ErrorAction Stop).Win32Shutdown(4) | out-null
|
|
Start-Sleep -s 5
|
|
Write-Host "User should now be logged off." -ForegroundColor Green
|
|
|
|
}
|
|
|
|
Catch
|
|
{
|
|
Write-Host "Could not connect to the target [$ComputerName]. `nPlease verify that the computer is still powered on and is on the Samaritan network." -ForegroundColor Yellow -BackgroundColor Red
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#This only happens if the user selects "No." Displays a message, then exits the script.
|
|
1{
|
|
Write-host "Canceling logging off user." -ForegroundColor Yellow
|
|
|
|
}
|
|
}
|
|
|
|
} |