Home > Mobile >  Powershell For each Write-EventLog
Powershell For each Write-EventLog

Time:11-19

In my code I have a for-each loop, which writes a line to the event viewer log - this is fine for small runs but on larger runs where "each" is a large number its too many events. How can I only write the log entry after every 10'th pass through the loop or maybe time based?

Thanks

CodePudding user response:

You can use the remainder operator % (sometimes referred to as the modulus or modulo operator) to only do something on every n'th iteration:

$loopCounter = 0

Get-LargeNumberOfItems |ForEach-Object {
  if(  $loopCounter % 10 -eq 1){
    Write-EventLog -LogName Application -Source TonysEventSource -EventId 123 -Message "We're on the ${loopCounter}th iteration now..."
  }

  # do actual processing of $_
}

This will write to the event log on the first iteration, the eleventh, the twentyfirst etc., because the remainder of 1, 11 and 21 divided by 10 is 1 in each case, thus satisfying $loopCounter % 10 -eq 1

  • Related