Many times I feel the need of Infinite loops for testing purposes, to catch an occurrence of an event or while stress testing applications, service or some specific processes.

DEFINITION : An infinite loop (also known as an endless loop or unproductive loop) is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.

I personally think Infinite loops can be great utility for System Admins, and could be utilized for temporary monitoring of running applications, specific services and process under stress conditions.

HOW TO MAKE INFINITE LOOPS : 

Well, there could be probably many ways, following are some I’m aware of

1. FOR Loops without conditions

Leaving the conditions empty makes its conditional check TRUE on every iteration and loop runs infinitely.

For

2. While Loops with $true as condition

While loops are Entry controlled loops, and body is executed if condition is TRUE on the top.

while

3. DO WHILE Loop with $true as condition

Do While is an Exit controlled loop where body is excuted first then condition is checked at the bottom and will iterate if Bottom condition is TRUE.

dowhile

4. RECURSION

Recursion is when the a function calls itself inside its body, which creates and endless loop

Where, Callee Function = Called function

recurse

Initially, I thought it was a great idea like in other programming languages, but Recursion has some limitations in powershell and it will not run endlessly due to depth overflow, to know about depth overflow refer THIS article, but we could use recursion where we have to make lesser number of iterations.

EXAMPLE 1 : 

I’m want to stress test an running process on my machine , under defined criteria and break the loop when the threshold is breached. I could achieve it in the following manner.

stress

it will give the output somewhat like this.

stress

EXAMPLE 2 : 

Suppose I’m going to schedule SQL backup to run 9 PM everyday on a machine but before that I want to  test if the memory or CPU utilization when the backup is running, crosses the defined threshold.

In this case, just like in the above example we can fire an infinite loop until our powershell session lasts, during the time frame test backup is running to collect the CPU or Memory utilization for the SQL process. Or we can break the infinite loop when threshold is breach ( ~ using Break keyword )

Happy Reading Folks ! 🙂  Have a nice day ahead.