Share via


PowerShell Tips and Tricks: Using Loops

Question: How to use Loops in PowerShell?

Answer: do while {} , for {} , foreach {}. We can choose as required for the scripting bu we should choose the best and logical one that suits our environment.

Demo: Print any text 5 times on the screen. Choose your best method

Many Opted for the below method using do while {}
Logic 1:


$i = 1
do {
Write-Host "PowerShell"
$i++
}
while ($i -le 5)

Whats wrong in this? Nothing but PowerShell can do this in very smart way. See the code below
Logic 2




$text = "PowerShell"
1..5 | %{$text}

The requirement is very simple so I opted the second method. But ended up with so much of confusions and questions from my team fellow.

  1. Your script can't get variables from the script execution or users can't pass the variable.
  2. No Write-Host so you can't print using foreground color.
  3. The quality is not great.

What made you to opt this logic?
I answered, because it's simple. We should know how to adopt the Power of Shell :)

I don't want to reply for Quality because nothing is bad here :).

My Final Code may answer you all
Logic 3




$times = Read-Host "Enter an integer value"
$text = Read-Host "Enter your Text"
1..$times | %{Write-Host $text -ForegroundColor Green}