如何使用 Powershell 从 Windows 事件日志中读取登录和注销事件,并从 Active Directory 中检索每个用户的相应信息?
最佳答案
以下脚本将从系统日志中读取 Winlogon 事件,根据每个用户的 SID 从 AD 检索信息,并在生成的 HTML 页面中显示结果。每次 AD 查找的结果都会被缓存,以防止不必要的 AD 服务器往返。
# event id 7001 is Logon, event id 7002 is Logoff
function WinlogonEventIdToString($EventID) {switch($EventID){7001{"Logon";break}7002{"Logoff";break}}}
# look up SID in Active Directory and cache the results in a hashtable
$AdUsers = @{}
function SidToAdUser($sid) {
$AdUser = $AdUsers[$sid]
if ($AdUser -eq $null) {
$AdUser = $AdUsers[$sid] = [adsi]("LDAP://<SID=" + $sid + ">")
}
return $AdUser
}
$outputFilename = [System.IO.Path]::GetTempPath() + "DisplayLatestLogonEvents.html"
# the first Select extracts the SID from the event log entry and converts the event id to a descriptive string
# the second Select is responsible for looking up the User object in Active Directory, using the SID
# the final Select picks the various attribute data from the User object, ready for display in the table
# to retrieve only recent log entries, one can use something like this in Get-EventLog: -After (Get-Date).AddDays(-14)
Get-Eventlog -Logname "System" -Source "Microsoft-Windows-Winlogon" -InstanceId 7001,7002 `
| Select TimeGenerated, @{n='Operation';e={WinlogonEventIdToString $_.EventID}}, @{n='SID';e={$_.ReplacementStrings[1]}} `
| Select TimeGenerated, Operation, @{n='AdUser';e={(SidToAdUser $_.SID)}} `
| Select TimeGenerated, Operation, `
@{n='Username';e={$_.AdUser.sAMAccountName}}, `
@{n='Full name';e={$_.AdUser.firstname + " " + $_.AdUser.lastname}}, `
@{n='Title';e={$_.AdUser.title}}, `
@{n='Department';e={$_.AdUser.department}}, `
@{n='Company';e={$_.AdUser.company}} `
| ConvertTo-HTML -Head "<style>td, th { border:1px solid grey }</style>" | Out-File $outputFilename
# this will open the default web browser
Invoke-Expression $outputFilename
关于powershell - 如何使用 Powershell 读取登录事件并查找用户信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23810280/