powershell - 如何使用 Powershell 读取登录事件并查找用户信息?

标签 powershell authentication active-directory event-log winlogon

如何使用 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/

相关文章:

powershell - 在 Powershell 中设置 IIS 绑定(bind)证书时出现问题

javascript - Google Plus 登录 - 未知的 RPC 服务错误

powershell - 如何在 Windows 8.1 中安装 ActiveDirectory Powershell 模块?

c# - 如何在 Powershell 中模拟 Active Directory 用户?

java - 为什么 SpringLDAP/普通 Java AD 查询中的 accountExpires 和 userAccountControl 过滤器不能按预期工作?

powershell - 我可以使用 powershell "draw"/创建具有给定文本的图像吗?

powershell - Powershell陷阱和处理中的功能错误

exception - 简单的 Try/catch 不起作用

ruby-on-rails - 我可以将 devise encrypted_pa​​ssword 与自定义身份验证一起使用吗?

linux - 在 Angstrom Linux 上自动登录