我正在尝试编写一个 .bat 脚本,该脚本将在远程桌面闲置 24 小时后注销用户。该脚本在 59 分钟内运行良好,但在数小时内无法执行相同的操作。无法进行转换。这里它会在 5 分钟后注销空闲用户。
@echo off
:Top
for /f "tokens=1-7 delims=,: " %%a in ('query user ^| find /i "disc"') do if %%d GTR 5 (logoff %%b) else %%e GTR 5 (logoff %%b)
choice /T 120 /C 1 /D 1 /N
goto top
我也想介绍这个场景,因为这个批处理脚本将从任务计划程序每四个小时运行一次。
请尝试一下,我只将
%%e
分配给 val
,因为这是我系统上的令牌位置,所以如果您当时处于空闲时间,请随意设置 val=%%d
。正如我提到的,我无法测试这一点,因为我没有相同的环境。
@echo off
:Top
for /f "tokens=1-7 delims=,: " %%a in ('query user ^| find /i "disc"') do set "val=%%e"
for /f "tokens=1,* delims=:" %%i in ("%val%") do if %%i GEQ 23 if %%j GTR 58 logoff %%b
choice /T 120 /C 1 /D 1 /N
goto top
以下是完成该工作的 powershell 脚本:
if($server -eq $null){
$server = "localhost"
}
$users = @()
# Query using quser, 2>$null to hide "No users exists...", then skip to the next server
$quser = quser /server:$server 2>$null
if(!($quser)){
Continue
}
#Remove column headers
$quser = $quser[1..$($quser.Count)]
foreach($user in $quser){
$usersObj = [PSCustomObject]@{Server=$null;Username=$null;SessionName=$null;SessionId=$Null;SessionState=$null;LogonTime=$null;IdleTime=$null}
$quserData = $user -split "\s+"
#We have to splice the array if the session is disconnected (as the SESSIONNAME column quserData[2] is empty)
if(($user | select-string "Disc") -ne $null){
#User is disconnected
$quserData = ($quserData[0..1],"null",$quserData[2..($quserData.Length -1)]) -split "\s+"
}
# Server
$usersObj.Server = $server
# Username
$usersObj.Username = $quserData[1]
# SessionName
$usersObj.SessionName = $quserData[2]
# SessionID
$usersObj.SessionID = $quserData[3]
# SessionState
$usersObj.SessionState = $quserData[4]
# IdleTime
$quserData[5] = $quserData[5] -replace "\+",":" -replace "\.","0:0" -replace "Disc","0:0"
if($quserData[5] -like "*:*"){
$usersObj.IdleTime = [timespan]"$($quserData[5])"
}elseif($quserData[5] -eq "." -or $quserData[5] -eq "none"){
$usersObj.idleTime = [timespan]"0:0"
}else{
$usersObj.IdleTime = [timespan]"0:$($quserData[5])"
}
# LogonTime
$usersObj.LogonTime = (Get-Date "$($quserData[6]) $($quserData[7]) $($quserData[8] )")
$users += $usersObj
if($usersObj.idleTime -ge [timespan]"23:58" -and $usersObj.SessionState -eq "Disc")
{
Logoff $quserData[3]
}
}
return $users
}
$quer= Get-LoggedOnUsers````
此代码不起作用,我尝试过,我需要类似的解决方案 RDP 即使在 1 小时后也应该存在,但我找不到任何好的脚本或 bat 文件。请帮忙