0

我编写了 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 } }
}
4

2 回答 2

0

您的固定代码是:

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-object请注意,我添加了和select-objectcmdlet中缺少的几个下划线,并且需要-first 1after的一个结果select-object

于 2019-12-24T14:35:06.200 回答
0

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

# 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

请参阅:审核登录事件

于 2019-12-24T14:36:34.163 回答