Thursday 30 June 2016

More about Loops in PowerShell

Do Until

The logic of this loop is to execute the Do {block} until (the condition is true).

As usual in PowerShell, pay close attention to the style of brackets, the curly brackets or parentheses guides you to write the correct code.

PS-L-1

Note: Don't try: Until ($strQuit = "N").  You need here to use -eq, this is PowerShell's way of comparing two values.

Do While

The logic of 'Do ... While' is the opposite of the Do Until. {Execute the block statement} while the (condition is true)
PS-L-1

Note: There are difference between until & while in above two examples: Until ($strQuit -eq "N") While ($strQuit -ne "N")

 

'While' on Its Own - No Explicit 'Do'

This method is the more traditional way with the (condition) followed by the {Block command}.  Clearly, PowerShell's While loop is simpler and more basic than the 'Do ... While' construction in above two examples.

PS-L-1

Note: In this example the 'While' clause is at the beginning instead of the end.

 

'For' Loop

Below example is a simple method using the keyword ‘For’. As usual there is a (condition) and {Block Statement}.

The speciality of this loop is the <init> and <repeat> sections.

Here is the syntax:

For (<init>; <condition>; <repeat>) {<command_block>}

Example: Times Table for 25

PS-L-1

One side-effect of the For loop is that it always returns the <init> before it tests for the condition.

The <repeat> modifies the $i variable, which is then tested inside the <condition> of the next cycle.

 

'Foreach' loop

The PowerShell 'Foreach' loop is more complex, and has more arguments than the 'for' and 'Do While' loops.  The key feature is that the loop interrogates an array, known as a collection.  It then applies a {Statement Block} to each iteration.  In addition to the position and the type of bracket, observe the tiny, but crucial keyword - 'In'.

 

PS-L-1

 

PS-L-1

# PowerShell ForEach loop to display files in C:\Program files

$Path = "C:\Program Files\" "{0,10} {1,-24} {2,-2}" -f ` " Size", "Last Accessed", "File Name " Foreach ($file in Get-Childitem $Path -recurse -force) {If ($file.extension -eq ".txt")     {     "{0,10} {1,-24} {2,-2}" -f `     $file.length, $file.LastAccessTime, $file.fullname     } }

 

# PowerShell ForEach-Objcet piping into block statement

Clear-Host $Path = "C:\Program Files\" Get-Childitem $Path -recurse -force | Foreach-Object {If ($_.extension -eq ".txt") {Write-Host $_.fullname        } }

 

PS-L-1

 

PS-L-1

 

I will come up with more stuffs in my upcoming posts.

Till then keep practicing and stay tuned for more details.

No comments:

Post a Comment