Overview
PowerShell functions are helpful in saving time when you have repetitive task(s) to be executed. In this guide we will demonstrate, as to how to construct a “for” loop with different incremental and decremented values.
Applies To
Tested on Windows 10, Windows 2008 R2 and Windows 2012.
Pre-Requisites
Launch PowerShell Command Console or PowerShell ISE.
To run this script, Execution Policy should be set to either of these “AllSigned” or “RemoteSigned” or “Unrestricted”, you can get current execution policy by running the command; “Get-ExecutionPolicy”.
Each Policy type and its purpose is shown in the below table.
Policy Type |
Purpose |
Restricted |
No scripts can be run. Windows PowerShell can be used only in interactive mode. |
AllSigned |
Only scripts signed by a trusted publisher can be run. |
RemoteSigned |
Downloaded scripts must be signed by a trusted publisher before they can be run. |
Unrestricted |
No restrictions; all Windows PowerShell scripts can be run. |
PowerShell Script – For Loop
This PowerShell script demonstrates the usage of
for loop in a PowerShell.
Code Snippet - For Loop
The code snippet is for demonstrating “for” loop usage, wherein
incremental and
decremented values are demonstrated.
Clear-Host
Write-Host "Increment by 1 for loop" -BackgroundColor Green -ForegroundColor White
#
# Increment by 1
#
for($Iterator=0; $Iterator -le 5; $Iterator++) {
Write-Host "Increment by 1 - Current Incremental Value " $Iterator
[console]::Beep(65, 100)
}
#
# Skip +2 or Increment by 2
#
Start-Sleep -Seconds 2
Write-Host "`nIncrement by 2 for loop" -BackgroundColor Green -ForegroundColor White
for($Iterator=0; $Iterator -le 10; $Iterator += 2) {
Write-Host "Increment by 2 - Current Incremental Value" $Iterator
[console]::Beep(37, 100)
}
#
# Decrement by 1
#
Start-Sleep -Seconds 2
Write-Host "`nDecrement by 1 for loop" -BackgroundColor Green -ForegroundColor White
for($Iterator=0; $Iterator -ge -5; $Iterator--) {
Write-Host "Decrement by 1 - Current Decremented Value" $Iterator
[console]::Beep(37, 100)
}
#
# Skip -2 or Decrement by 2
#
Start-Sleep -Seconds 2
Write-Host "`n Skip -2 or Decrement by 2 for loop" -BackgroundColor Green -ForegroundColor White
for($Iterator=0; $Iterator -ge -10; $Iterator -= 2) {
Write-Host "Decrement by 2 - Current Decremented Value" $Iterator
[console]::Beep(37, 100)
}
PowerShell Output – For loop
The code snippet is for demonstrating “
for” loop usage, wherein incremental and decremented values are demonstrated.
SlideShare Information
A step by step guide is uploaded to slideshare.
No comments:
Post a Comment