Dominic Brunetti
Dominic Brunetti

Reputation: 1069

Pausing in batches during a foreach loop?

I'm writing a script to migrate 500+ DNS records to Windows 2008 (from '03) and then manipulating attributes - all via DNSCMD (builtin MS DNS tool).

Anyways - there is a limitation in DNS where if you do things "too fast" it starts choking on itself - I've seen this before in my old DOS scripts.

That said, how would I batch up a foreach loop?

Like for example (in laymans terms w/ scripting)

$records = C:\myfile.txt

foreach ($record in records) {
     MyFunction (only to the first 20 records)
     start-sleep 2
     MyFunction (to the next 20 records)
... etc .... 
    }

Is that possible? If so how would you approach it? I guess I could add a simple start-sleep 1 after MyFunction, but with 500+ records, times many functions, that's gonna take a VERY long time. :( I think batching them is the best in terms of efficiency we've found from the DOS world. Thanks!

Upvotes: 0

Views: 1161

Answers (1)

mjolinor
mjolinor

Reputation: 68303

If you're reading them from a file, you can batch them up using -ReadCount:

Get-Content C:\myfile.txt -ReadCount 20 |

foreach {
 foreach ($record in $_) 
   { MyFunction $record }
 start-sleep 2
 }

Upvotes: 5

Related Questions