Read/Delete/Move Every X. File

by Jan 17, 2012

Occasionally, you may want to act on every 2nd or 3rd file in a folder (or line in a file). The easiest way to identify every x. element is to use the "%" (modulus) operator.

This will list every 5th file in the Windows folder (for what it's worth):

PS> Dir $env:windir | ForEach-Object { $x=0 } { $x++ if ($x % 5 -eq 0) { $_ } }

And this would read every 50th line from windowsupdate.log:

PS> Get-Content $env:windir\windowsupdate.log | ForEach-Object { $x=0 } { $x++ if ($x % 50 -eq 0) { $_ } }

It's always the same procedure: ForEach-Object implements a counter in $x, and only if the current counter is dividable by the increment you want (% returns 0) will the object be returned. Now it's just up to you to find use cases for this.

Twitter This Tip! ReTweet this Tip!