Как написать список уникальных результатов для каждого цикла в Powershell? - PullRequest
0 голосов
/ 19 сентября 2019

В следующем коде я получаю список повторяющихся значений.Я пытаюсь иметь только одну строку для каждой дублируемой строки, отличной.

Это код:

# Find DC list from Active Directory
$DCs = Get-ADDomainController -Filter *

# Define time for report (default is 1 day)
$startDate = (get-date).AddDays(-1)

# Store successful logon events from security logs with the specified dates and workstation/IP in an array
foreach ($DC in $DCs){
$slogonevents = Get-Eventlog -LogName Security -ComputerName $DC.HostName  -after $startDate -InstanceId 4624 | where {$_.ReplacementStrings[5].ToLower() -eq "administrator"}

# Crawl through events; print all logon history with type, date/time, status, account name, computer and IP address if user logged on remotely

  foreach ($e in $slogonevents){            
    if ($e.EventID -eq 4624 -and $e.ReplacementStrings[8] -In 3..10){            
      if([ipaddress]::TryParse($e.ReplacementStrings[18],[ref][ipaddress]::Loopback))
      {
        $type = $e.ReplacementStrings[8]
        $ip = $e.ReplacementStrings[18]
        $hostname=([system.net.dns]::GetHostByAddress($ip)).HostName

        write-host "Type:" $type "`tIP Address: " $ip  "`tHost Name: " $hostname             
      }
    }
  }
} Get-Unique #this does not work, also tried Unique

Я получаю вывод, похожий на следующий "

Type: 3  IP Address: 192.168.1.1 Host Name: ABCD
Type: 3  IP Address: 192.168.1.1 Host Name: ABCD
Type: 3  IP Address: 192.168.1.1 Host Name: ABCD
Type: 3  IP Address: 192.168.1.2 Host Name: EFGH
Type: 3  IP Address: 192.168.1.2 Host Name: EFGH
Type: 3  IP Address: 192.168.1.2 Host Name: EFGH
Type: 3  IP Address: 192.168.1.1 Host Name: ABCD

Хотелось бы получить:

Type: 3  IP Address: 192.168.1.1 Host Name: ABCD
Type: 3  IP Address: 192.168.1.2 Host Name: EFGH

1 Ответ

1 голос
/ 19 сентября 2019

Я думаю, что причина, по которой вы не получаете уникальные значения, заключается в том, что вы пишете на хост в своем цикле foreach до Unique.По сути, выписать их до того, как они узнают, что такое unique

. Я бы создал PSCustomObject и назначил его в вашем foreach.Это позволит вам позвонить позже, используя | Select -Unique

# Find DC list from Active Directory
$DCs = Get-ADDomainController -Filter *

# Define time for report (default is 1 day)
$startDate = (get-date).AddDays(-1)

# Store successful logon events from security logs with the specified dates and workstation/IP in an array
foreach ($DC in $DCs){
$slogonevents = Get-Eventlog -LogName Security  -after $startDate -InstanceId 4624 | where {$_.ReplacementStrings[5].ToLower() -eq "administrator"}

# Crawl through events; print all logon history with type, date/time, status, account name, computer and IP address if user logged on remotely

  foreach ($e in $slogonevents){  
     $report = @() 
    if ($e.EventID -eq 4624 -and $e.ReplacementStrings[8] -In 3..10){            
      if([ipaddress]::TryParse($e.ReplacementStrings[18],[ref][ipaddress]::Loopback))
      {
        $object = New-Object PSCustomObject -Property @{
            type = $e.ReplacementStrings[8]
            ip = $e.ReplacementStrings[18]
            hostname=([system.net.dns]::GetHostByAddress($($e.ReplacementStrings[18]))).HostName        
        }
        $report += $object
      }
    }
  }
}
$report | select -Unique
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...