PowerShell脚本获取登录详情问题:仅返回系统名需补充用户名
Hey there! Let's tweak your PowerShell script to pull both computer names and their associated logged-on users—here's how to make that happen:
What Was Missing in Your Original Script
Your current code only loads and outputs the computer name (cn) while filtering for Windows OS devices, but it doesn't include the AD attribute that stores the last logged-on user. We'll add that property and adjust the output to display both values clearly.
Modified PowerShell Script
Here's the updated version with comments explaining key changes:
function GetList { param ([string]$base) $blah = [ADSI]"$base" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.Filter = "(objectClass=Computer)" $objSearcher.SearchRoot = $blah # Added 'lastlogonusername' to fetch the last logged-on user from AD $PropList = "cn","operatingsystem","lastlogonusername" foreach ($i in $PropList){ $objSearcher.PropertiesToLoad.Add($i) } $Results = $objSearcher.FindAll() foreach ($objResult in $Results) { $OS = $objResult.Properties.operatingsystem If ($OS -match "Windows") { # Extract values, handle cases where no logon user is recorded $computerName = $objResult.Properties.cn[0] $loggedOnUser = if ($objResult.Properties.lastlogonusername) { $objResult.Properties.lastlogonusername[0] } else { "No logged-on user recorded" } # Output as a structured object for readability [PSCustomObject]@{ ComputerName = $computerName LastLoggedOnUser = $loggedOnUser } } } }
Key Updates Breakdown
- Added
lastlogonusernameAttribute: This AD property stores the username of the last user who logged into the computer. - Handled Empty Values: Some devices might not have a recorded last logon, so we default to a clear message instead of showing blank output.
- Structured Output: Using
[PSCustomObject]gives you a clean, tabular result that's easy to read or export to CSV later.
Bonus: Get Currently Active Logged-On Users
If you need the currently active user (not just the last one), the lastlogonusername attribute won't work. For that, you'll need to query each computer directly (requires admin access and network connectivity):
# Replace the logged-on user section in the loop with this: $loggedOnUser = try { Get-CimInstance -ComputerName $computerName -ClassName Win32_ComputerSystem -ErrorAction Stop | Select-Object -ExpandProperty UserName } catch { "Unable to query current user (check permissions/connectivity)" }
Just call your function like before (GetList -base "LDAP://your-domain-controller"), and you'll get the combined results you need!
内容的提问来源于stack exchange,提问作者Ram Prakash

