question

Proxiuz-8366 avatar image
0 Votes"
Proxiuz-8366 asked IanXue-MSFT edited

How do I add together the values from a table? (Powershell)

Hello!

My script is supposed to count the number of times different users succeeds and fails to login. The last part of the script should calculate how many % login fails each user have. Is there a good way to extract the values from each table? So it takes both values from each user and makes a "fails / success" calculation? Ive tried various Foreach loops but I never seem to get it right. Thanks in advance!


 $eventLog1 = Get-WinEvent -FilterHashTable @{logname="security";id=4768}
 $eventLog2 = Get-WinEvent -FilterHashTable @{logname="security";id=4771}
    
 $successLogins = @{}
    
 Foreach($event in $eventLog1)
 {
     $message = $event.Message
     $user = $message.Split()[17]
    
     if($user -match '\$$'){continue}
        
     $successLogins[$user] += 1
 }
 Write-Host "---Successfull logins---" -Fo Green
 $successLogins 
    
 $failedLogins = @{}
    
 Foreach($event in $eventLog2)
 {
     $message = $event.Message
     $user = $message.Split()[19]
    
     if($user -match '\$$'){continue}
        
     $failedLogins[$user] += 1
 }
 Write-Host "                   " -Fo Red
 Write-Host "---Failed logins---" -Fo Red
 $failedLogins 
    
    
 Write-Host "                     " -Fo Yellow
 Write-Host "---Failed logins %---" -Fo Yellow

Thanks in advance!

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered IanXue-MSFT edited

Hi,

To get the percentage of login failures you could try something like below.

 $result = @{}
 $allusers = $successLogins.Keys + $failedLogins.Keys | Select-Object -Unique
 $allusers | ForEach-Object {
     if($_ -notin $failedLogins.Keys){
         $percentage = 0
     }
     elseif($_ -notin $successLogins.Keys){
         $percentage = 100
     }
     else{
         $percentage = $failedLogins[$_]/($failedLogins[$_]+$successLogins[$_])*100
     }
     $result.Add($_,$percentage)
 }

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.