在数组中组合类似对象

时间:2014-12-03 19:18:52

标签: powershell

我正在尝试分析一组文本文件(MSFTP日志)并执行已提交错误凭据的IP地址计数。我想我已经解决了,除了我不认为数组正确传递给函数。因此,如果多个日志文件中出现相同的IP,我会收到重复的条目。我做错了什么?

Function LogBadAttempt($FTPLog,$BadPassesArray)
    {
    $BadPassEx="PASS - 530"
    Foreach($Line in $FTPLog)
        {
        if ($Line -match $BadPassEx)
            {
            $IP=($Line.Split(' '))[1]
            if($BadPassesArray.IP -contains $IP)
                {
                $CurrentIP=$BadPassesArray | Where-Object {$_.IP -like $IP}
                [int]$CurrentCount=$CurrentIP.Count
                $CurrentCount++
                $CurrentIP.Count=$CurrentCount
                }else{
                $info=@{"IP"=$IP;"Count"='1'}
                $BadPass=New-Object -TypeName PSObject -Property $info
                $BadPassesArray += $BadPass
                }
            }
        }
    return $BadPassesArray
    }
$BadPassesArray=@()
$FTPLogs = Get-Childitem \\ftpserver\MSFTPSVC1\test
$Result = ForEach ($LogFile in $FTPLogs)
    {
    $FTPLog=Get-Content ($LogFile.fullname)
    LogBadAttempt $FTPLog
    } 
$Result | Export-csv C:\Temp\test.csv -NoTypeInformation

结果看起来像......

Count   IP
7   209.59.17.20
20  209.240.83.135
18441   209.59.17.20
13059   200.29.3.98

并希望它将209.59.17.20

的条目组合在一起

1 个答案:

答案 0 :(得分:3)

你让这个方式太复杂了。处理管道中的文件并使用哈希表来计算每个IP地址的出现次数:

$BadPasswords = @{}

Get-ChildItem '\\ftpserver\MSFTPSVC1\test' | Get-Content | ? {
  $_ -like '*PASS - 530*'
} | % {
  $ip = ($_ -split ' ')[1]
  $BadPasswords[$ip]++
}

$BadPasswords.GetEnumerator() |
  select @{n='IP';e={$_.Name}}, @{n='Count';e={$_.Value}} |
  Export-Csv 'C:\Temp\test.csv' -NoType