我编写了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 } }
}
答案 0 :(得分: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-object
cmdlet中添加了多个下划线,并且在-first 1
之后需要一个结果select-object
。
答案 1 :(得分:0)
如前所述,代码缺少$_
自动变量的下划线。
另外,我建议在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