我正在搜索一个简单的命令来查看服务器上登录的用户。 我知道这个:
Get-WmiObject -Class win32_computersystem
但这不会提供我需要的信息。 它返回: 域 Manufactureer 模型 名称(机器名称) PrimaryOwnerName TotalPhysicalMemory
我在Windows 2012服务器上运行Powershell 3.0。
另外
Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select Antecedent -Unique
没有给出我需要的确切答案。 我很乐意看到空闲时间,或者他们是否活跃或离开。
答案 0 :(得分:83)
为了寻找同样的解决方案,我在stackoverflow中的不同问题下找到了我需要的东西: Powershell-log-off-remote-session。下面一行将返回登录用户列表。
query user /server:$SERVER
答案 1 :(得分:19)
没有“简单的命令”来做到这一点。您可以编写一个函数,也可以选择在各种代码存储库中在线提供的函数。我用这个:
function get-loggedonuser ($computername){
#mjolinor 3/17/10
$regexa = '.+Domain="(.+)",Name="(.+)"$'
$regexd = '.+LogonId="(\d+)"$'
$logontype = @{
"0"="Local System"
"2"="Interactive" #(Local logon)
"3"="Network" # (Remote logon)
"4"="Batch" # (Scheduled task)
"5"="Service" # (Service account logon)
"7"="Unlock" #(Screen saver)
"8"="NetworkCleartext" # (Cleartext network logon)
"9"="NewCredentials" #(RunAs using alternate credentials)
"10"="RemoteInteractive" #(RDP\TS\RemoteAssistance)
"11"="CachedInteractive" #(Local w\cached credentials)
}
$logon_sessions = @(gwmi win32_logonsession -ComputerName $computername)
$logon_users = @(gwmi win32_loggedonuser -ComputerName $computername)
$session_user = @{}
$logon_users |% {
$_.antecedent -match $regexa > $nul
$username = $matches[1] + "\" + $matches[2]
$_.dependent -match $regexd > $nul
$session = $matches[1]
$session_user[$session] += $username
}
$logon_sessions |%{
$starttime = [management.managementdatetimeconverter]::todatetime($_.starttime)
$loggedonuser = New-Object -TypeName psobject
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Session" -Value $_.logonid
$loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $logontype[$_.logontype.tostring()]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage
$loggedonuser | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $starttime
$loggedonuser
}
}
答案 2 :(得分:9)
由于我们已经进入PowerShell领域,如果我们可以返回正确的PowerShell对象,它会非常有用......
我个人喜欢这种解析方法,为了简洁:
SELECT master.sid
,master.cid
,master.year1
,c.name1
FROM sales master
INNER JOIN car c ON master.cid = c.id --(1st)
SELECT s.sid
,s.cid
,s.year1
,c.name1
FROM sales s
INNER JOIN car c ON s.cid = c.id --(2nd)
注意: 这不会影响已断开连接的用户("光盘"),但如果您只是想要,则效果不错获取快速的用户列表,而不关心其他信息。我只是想要一个清单,如果他们目前已经断开连接,我们就不在乎了。
如果你关心其他数据,那就更复杂了:
((quser) -replace '^>', '') -replace '\s{2,}', ',' | ConvertFrom-Csv
I take it a step farther and give you a very clean object on my blog.
答案 3 :(得分:4)
也许你可以用
做点什么 get-process -includeusername
答案 4 :(得分:1)
如果您想找到交互式登录用户,我在这里找到了一个很棒的提示:https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/(Win32_ComputerSystem没有帮助我)
$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
"No explorer process found / Nobody interactively logged on"
}
Else
{
ForEach ($i in $explorerprocesses)
{
$Username = $i.GetOwner().User
$Domain = $i.GetOwner().Domain
Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
}
}
答案 5 :(得分:1)
以下是我的方法,基于DarKalimHero的建议,只选择Explorer.exe进程
Function Get-RdpSessions
{
param(
[string]$computername
)
$processinfo = Get-WmiObject -Query "select * from win32_process where name='explorer.exe'" -ComputerName $computername
$processinfo | ForEach-Object { $_.GetOwner().User } | Sort-Object -Unique | ForEach-Object { New-Object psobject -Property @{Computer=$computername;LoggedOn=$_} } | Select-Object Computer,LoggedOn
}
答案 6 :(得分:0)
这是我刚刚想出来的,效果很好!
variables
答案 7 :(得分:0)
另一种解决方案,同样基于 query user
,但可以处理 variations in culture(据我所知)并产生强类型结果(即 TimeSpan 和 DateTime 值):
# Invoke "query user", it produces an output similar to this, but might be culture-dependant!
#
# USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
# >jantje rdp-tcp#55 2 Active . 3/29/2021 4:24 PM
# pietje 4 Disc 49+01:01 4/14/2021 9:26 AM
$result = (&query 'user' | Out-String -Stream)
# Take the header text and insert a '|' before the start of every HEADER - although defined as inserting a bar after
# every 2 or more spaces, or after the space at the start.
$fencedHeader = $result[0] -replace '(^\s|\s{2,})', '$1|'
# Now get the positions of all bars.
$fenceIndexes = ($fencedHeader | Select-String '\|' -AllMatches).Matches.Index
$timeSpanFormats = [string[]]@("d\+hh\:mm", "h\:mm", "m")
$entries = foreach($line in $result | Select-Object -Skip 1)
{
# Insert bars on the same positions, and then split the line into separate parts using these bars.
$fenceIndexes | ForEach-Object { $line = $line.Insert($_, "|") }
$parts = $line -split '\|' | ForEach-Object { $_.Trim() }
# Parse each part as a strongly typed value, using the UI Culture if needed.
[PSCustomObject] @{
IsCurrent = ($parts[0] -eq '>');
Username = $parts[1];
SessionName = $parts[2];
Id = [int]($parts[3]);
State = $parts[4];
IdleTime = $(if($parts[5] -ne '.') { [TimeSpan]::ParseExact($parts[5], $timeSpanFormats, [CultureInfo]::CurrentUICulture) } else { [TimeSpan]::Zero });
LogonTime = [DateTime]::ParseExact($parts[6], "g", [CultureInfo]::CurrentUICulture);
}
}
# Yields the following result:
#
# IsCurrent Username SessionName Id State IdleTime LogonTime
# --------- -------- ----------- -- ----- -------- ---------
# True jantje rdp-tcp#32 2 Active 00:00:00 3/29/2021 4:24:00 PM
# False pietje 4 Disc 48.11:06:00 4/14/2021 9:26:00 AM
$entries | Format-Table -AutoSize