Invoke-Logoff
Invoke-Logoff
Logoff a target User
By Michael J. Thomas
<#
.Synopsis
Logoff User off a Remote Computer.
.DESCRIPTION
Invoke-Logoff v1.0 Used to Logoff a User from a Remote Computer.
This also tests if a computer is online and if WinRM is enabled.
Created by Michael J. Thomas 9/11/2018.
Updated 12/27/2018
.EXAMPLE
Invoke-Logoff -ComputerName "computer01" -UserName "user01"
#>
Function Invoke-Logoff
{
[cmdletbinding()]
param (
[String]$ComputerName,
[String]$UserName
#[Parameter(Mandatory = $true)]
)
Function Get-QUser
{
[cmdletbinding()]
param (
[String]$ComputerName = $env:COMPUTERNAME
)
If ($ComputerName -eq $env:COMPUTERNAME)
{
$Out = quser.exe
}
Else
{
$Out = Invoke-Command -ComputerName $ComputerName -ScriptBlock { quser.exe }
If (!$Out) { Throw "Unable to retrieve quser info for `"$ComputerName`"" }
}
ForEach ($ln in $Out)
{
[PSCustomObject]@{
Username = $ln.SubString(1, 20).Trim()
SessionName = $ln.SubString(23, 17).Trim()
ID = $ln.SubString(42, 2).Trim()
}
}
}
If (Test-Connection -Computername $ComputerName -BufferSize 16 -Count 1 -Quiet)
{
Write-Host "$ComputerName is OnLine" -ForegroundColor Green
If (Test-WSMan -ComputerName $ComputerName -ErrorAction SilentlyContinue)
{
Write-Host "WinRM Configured" -ForegroundColor Green
Try
{
$FindUser = (Get-QUser -ComputerName $ComputerName) | Where-Object { $_.Username -like "*$UserName*" }
If ($FindUser.Username -eq $UserName)
{
Write-Host "$UserName is Logged Into the $ComputerName" -ForegroundColor Green
Start-Sleep 2
$ID = $FindUser.ID
Write-Host $(Invoke-Command -ComputerName $ComputerName -ScriptBlock { Logoff $Using:ID /v }) -ForegroundColor Green
}
Else
{
Write-Host "$UserName is Not Logged Into the $ComputerName" -ForegroundColor Yellow
Get-QUser -ComputerName $ComputerName
}
}
Catch
{
Write-Host = "$UserName Does Not Exist on $ComputerName"
Get-QUser -ComputerName $ComputerName
}
}
Else
{
#WinRM is not Configured
Write-Host "WinRM Not Configured" -ForegroundColor Yellow
}
}
Else
{
Write-Host "$ComputerName is Offline" -ForegroundColor Yellow
}
}
Comments
Post a Comment