我想要一种简单的方法来让我的列表中所有服务器上的所有(远程)登录(和断开连接)用户。
为此,我使用 QUERY SESSION 命令(因为我发现它是最快和最可靠的命令)。该命令在我的代码中称为 QWINSTA(与 QUERY SESSION 相同),适用于 Windows 2012 及更高版本。
但是使用我的脚本,我将获得(服务器名称、会话名称、会话 ID 和会话状态)的详细信息,但我还需要用户 IDOL 时间和用户登录时间,但我觉得使用 QWINSTA 我们无法做到这一点,使用 QUER用户我们可以得到这些细节。
有人可以帮我在我的输出中获取所有这些详细信息(用户名、会话名、ID、状态、空闲时间、登录时间)
下面是我的代码。
代码
## Clear Host Console
Clear-Host
## Define Variable for Server Count
$z = 0
##Set Default Script Location
Set-Location -Path "C:\Users\reddy\Desktop\Active or Disc users"
## Provide List of Servers to Check for the Disconnected user session
$Servers = Get-Content ".\Servers\AZ_Servers.txt"
## Get Servers Count
$count = $Servers.count
## Define Date for the Out file
$dt = Get-Date -Format yyyyMMdd
$Date = Get-Date
## Define Path for the Out File
$exportFile = ".\Out\RDP_DisConnected_Users.csv"
## Define Array for Storing the User sessions
$openSessions = @()
## Loop through each server to find the User Disconnected session
Foreach ($ServerName in $Servers)
{
#initiate counter for showing progress
$z = $z + 1
# Start writing progress
Write-Progress -Activity "Processing Server: $z out of $count servers." -Status " Progress" -PercentComplete ($z/$Servers.count*100)
## Add the servers if you want to exclude any
$ExcludedServers = "EXCLUDESRV01", "EXCLUDESRV02", "EXCLUDESRV03"
If ($ExcludedServers -notcontains $ServerName)
{
Write-Host "Getting session information for $ServerName"
$sessions = qwinsta /server $ServerName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "ServerName", "Username", "Id", "State"
$item.ServerName = $ServerName
#$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item
}
$openSessions += $sessions | where { ($_.Username -ne "") -and ($_.Username -ne "Administrator") -and ($_.State -ne "Active")}
}
Else { Write-Host "Skipping named computer $ServerName" -ForegroundColor Green}
}
$openSessions | Export-Csv "$exportFile" -NoTypeInformation