windows上powershell获取登录日志

admin2023-12-11windows23
# 获取从9月到现在的登录事件日志
$loginEvents = Get-EventLog -LogName Security -InstanceId 4624 -After (Get-Date -Year 2023 -Month 9 -Day 1) | Where-Object {$_.ReplacementStrings[5] -eq "Administrator"}
# 创建一个空数组,用于存储登录事件信息
$eventArray = @()
# 遍历登录事件日志并提取感兴趣的远程细节信息
foreach ($event in $loginEvents) {
    $time = $event.TimeGenerated
    $username = $event.ReplacementStrings[5]
    $sourceIP = $event.ReplacementStrings[18]
    $sourceWorkstation = $event.ReplacementStrings[11]
    
    # 将登录事件信息添加到数组中
    $eventArray += [PSCustomObject]@{
        "登录时间" = $time
        "用户名" = $username
        "源IP地址" = $sourceIP
        "源工作站" = $sourceWorkstation
    }
}
# 构建桌面上的文件路径
$desktopPath = [System.IO.Path]::Combine($home, "Desktop\login_events.csv")
# 将数组输出到 CSV 文件中
$eventArray | Export-Csv -Path $desktopPath -Encoding UTF8 -NoTypeInformation