如何筛选 EventLog 以每天获取一个日志 - PowerShell

How to Filter EventLog to get one log per a day - PowerShell

我编写了 powershell 脚本来获取特定用户的登录位置。 但是我想每天只得到一个结果

脚本运行完美,但每天给出很多结果。

这是我的脚本:

$StartDate = Get-Date -Year 2019 -Month 12 -Day 01 
$computers = Get-ADComputer -SearchBase 'ou=XXX,dc=XXX,dc=org,dc=XX' -Filter "Name -like 'XXXX*'" 
foreach ($comp in $computers) { 
    $Computer = $comp.Name 
    Get-WinEvent -max 3 -Computername $Computer -FilterHashtable @{LogName='Security';ID='4624' ;StartTime=$StartDate } | 
    where {($.Id -eq '4624') -and ($.properties[8].value -eq 3) -and ($.properties[5].value -eq 'XXXXX')} |
    select-Object -Property TimeCreated, MachineName , @{ Name = 'TargetUserName'; Expression = { $.Properties[5].Value } }
}

您的固定密码是:

StartDate = Get-Date -Year 2019 -Month 12 -Day 01 
$computers = Get-ADComputer -SearchBase 'ou=XXX,dc=XXX,dc=org,dc=XX' -Filter "Name -like 'XXXX*'" 
foreach ($comp in $computers) { $Computer = $comp.Name Get-WinEvent -max 3 -Computername $Computer -FilterHashtable 
@{LogName='Security';ID='4624' ;StartTime=$StartDate } | where {($_.Id -eq '4624') -and ($_.properties[8].value -eq 3) -and ($._properties[5].value -eq 'XXXXX')} | select-Object -Property TimeCreated, MachineName , @{ Name = 'TargetUserName'; Expression = { $_.Properties[5].Value } } } -first 1

请注意,我添加了 where-objectselect-object cmdlet 中缺少的几个下划线,并且在需要 select-object 之后的一个结果 -first 1

如评论所述,代码缺少 $_ 自动变量的下划线。
另外,我建议在 startDate 上使用 .Date 来省略时间部分,有效地将其设置为午夜。

# set the startdate, remove the time part so it wil be the date at midnight
$StartDate = (Get-Date -Year 2019 -Month 12 -Day 01 ).Date
$LogonUser = 'XXXXX'
$computers = Get-ADComputer -SearchBase 'ou=XXX,dc=XXX,dc=org,dc=XX' -Filter "Name -like 'XXXX*'" 

foreach ($comp in $computers) { 
    $Computer =  $comp.Name 
    Get-WinEvent -Computername $Computer -FilterHashtable @{LogName='Security';ID=4624;StartTime=$StartDate } | 
    Where-Object {($_.Properties[8].Value -eq 3) -and ($_.Properties[5].Value -eq $LogonUser) } |
    Select-Object -Property TimeCreated, MachineName, 
                            @{ Name = 'TargetUserName'; Expression = { $_.Properties[5].Value } } |
    Group-Object @{Expression = {$_.TimeCreated.Date}} | ForEach-Object { 
        $_.Group | Select-Object -First 1
    }

对于那些想知道 $_.Properties 的人:

$_.Properties[5].Value --> TargetUserName
$_.Properties[8].Value --> LogonType. Value = 3 --> Network

参见:Audit logon events