如何解决使用 ForEach 循环计算 PowerShell 中安全日志文件 ID 的出现次数
我目前正在尝试使用 Powershell 中的 For Each 循环来计算日志文件中的某些出现次数。我已经尝试了同一个脚本的许多不同版本,但这就是我目前所拥有的:
$id = 4624
$instanceids = (get-eventlog security).instanceid
foreach ( $id in $instanceids ) {
$count ++
Write-Host " The amount of 4624's in the security log is $count"
}
我的问题是,循环计算有多少安全日志文件,而不是 Id 名为 4624 的日志文件。我不允许在这个不幸中使用 Measure-Object 或 .count。 感谢您抽出宝贵时间。
解决方法
如果您尝试计算特定 InstanceId 的出现次数:
$id = 4624
$InstanceIds = Get-EventLog -Logname Security -InstanceId $id
$Count = ( $InstanceIds | Measure-Object ).Count
Write-Host "The amount of 4624's in the security log is $count"
请注意,您可以使用 -InstanceId
参数来更有效地过滤。然后使用 Measure-Object
获取计数而不是自己循环。
为了说明您的循环出了什么问题,您没有进行有条件的计数。而且,您正在为每次循环迭代编写输出。这会奏效:
$id = 4624
$instanceids = (get-eventlog security).InstanceId
foreach ( $Instanceid in $instanceids ) {
If( $_.InstanceId -eq $id){ $count++ }
}
Write-Host " The amount of 4624's in the security log is $count"
注意:出于性能原因,最好将过滤移到左侧。因此,当 cmdlet 中有本机功能时,您应该尝试使用它。也就是说,如果您打算使用循环,它仍然可以比之前的示例更有效。
$id = 4624
Get-EventLog security -InstanceId $id |
ForEach-Object{ $count ++ }
Write-Host " The amount of 4624's in the security log is $count"
我还要指出 Get-WinEvent 是更新的,并且更胜任这类事情。 Get-EventLog 已从 PowerShell 7 中删除...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。