Tony
Tony

Reputation: 9571

Powershell For each Write-EventLog

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

Upvotes: 0

Views: 99

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

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

Upvotes: 1

Related Questions