Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save viniciusmelocodes/32a694c0c444c04ad825398ef657ebdd to your computer and use it in GitHub Desktop.
Save viniciusmelocodes/32a694c0c444c04ad825398ef657ebdd to your computer and use it in GitHub Desktop.
Faz logoff de todos usuários desconectados e salva mensagem de processo concluído. Rodar com privilégios de administrador.
# Logoff de usuários desconectados
# logoffUsuariosDesconectados.ps1
# Vinícius Lopes de Melo - 07/2021
# $>powershell.exe -noprofile -executionpolicy bypass -file C:\Temp\LogoffProgramado\logoffUsuariosDesconectados.ps1
#Requires -Version 2
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)]
[string[]]$ComputerName = $env:COMPUTERNAME
)
BEGIN {
# check that qwinsta.exe is present
$windir = $env:windir
if (!(Test-Path $windir\System32\qwinsta.exe)) {
Write-Host "qwinsta.exe not found"
break
}
}
PROCESS {
foreach ($computer in $ComputerName) {
# make an empty temporary object
$tmp = New-Object PSObject -Property @{
"SessionName" = 0
"UserName" = 0
"ID" = 0
"State" = 0
"Type" = 0
"Device" = 0
}
# run qwinsta to get session data
$sessions = (qwinsta /server:$computer)
# run through every line and storing the indexes of each "column" in the output
foreach ($line in $sessions) {
if ($line.Trim().Substring(0, $line.Trim().IndexOf(" ")) -eq "SESSIONNAME") {
$tmp.UserName = $line.IndexOf("USERNAME")
$tmp.ID = $line.IndexOf("ID")
$tmp.State = $line.IndexOf("STATE")
$tmp.Type = $line.IndexOf("TYPE")
$tmp.Device = $line.IndexOf("DEVICE")
continue
}
if (($line.Substring($tmp.State, $line.IndexOf(" ", $tmp.State) - $tmp.State).Trim() -eq 'Disc') -or ($line.Substring($tmp.State, $line.IndexOf(" ", $tmp.State) - $tmp.State).Trim() -eq 'Disco')) {
# logoff do usuário
$sessionId = ((quser /server:$computer | Where-Object { $_ -match $line.Substring($tmp.UserName, $line.IndexOf(" ", $tmp.UserName) - $tmp.Username) }) -split ' +')[2]
logoff $sessionId /server:$computer
}
}
}
}
END {
$dataHoje = Get-Date -Format "dd/MM/yyyy"
$horaAgoraCompleta = Get-Date -Format "HH:mm:ss"
"Logoff programado feito em: " + $dataHoje + " " + $horaAgoraCompleta | Out-File -FilePath "C:\Temp\LogoffProgramado\logoffProgramado.txt"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment