Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering PowerCLI

You're reading from   Mastering PowerCLI Master PowerCLI to automate all aspects of VMware environments

Arrow left icon
Product type Paperback
Published in Oct 2015
Publisher Packt
ISBN-13 9781785286858
Length 430 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Sajal Debnath Sajal Debnath
Author Profile Icon Sajal Debnath
Sajal Debnath
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. PowerShell and PowerCLI Refresher 2. Reusable Advanced Functions and Scripts FREE CHAPTER 3. Deploying vSphere Hosts 4. Managing Networks 5. Managing Storage 6. Managing Clusters and Other Constructs 7. Managing Virtual Machines 8. Managing vSphere Security, SRM, vCloud Air, and vROps 9. Managing the vSphere API 10. Using REST APIs 11. Creating Windows GUI 12. Best Practices and Sample Scripts Index

Implementing programming constructs in PowerShell

Since this is a book on mastering PowerCLI, I will assume that you already know the basics of the language. For example, how variables are declared in PowerShell and various restrictions on them. So, in this section, I am going to provide a short refresher on the different programming constructs and how they are implemented in PowerShell. I will deliberately not go into much detail. For details, check out https://technet.microsoft.com/en-us/magazine/2007.03.powershell.aspx.

In any programming language, the first thing that you need to learn about is the variables. Declaring a variable in PowerShell is pretty easy and straightforward; simply, start the variable name with a $ sign. For example, run the following code:

PS C:\> $newVariable = 10
PS C:\> $dirList = Dir | Select Name

Note that at the time of variable creation, there is no need to mention the variable type.

You can also use the following cmdlets to create different types of variable:

  • New-Variable
  • Get-Variable
  • Set-Variable
  • Clear-Variable
  • Remove-Variable

Best practice for variables is to initialize them properly. If they are not initialized properly, you can have unexpected results at unexpected places, leading to many errors. So, you can use Set-Strictmode in your script so that it can catch any uninitialized variables and thus remove any errors creeping in due to this. For details, check out https://technet.microsoft.com/en-us/library/hh849692.aspx.

When we started programming, we started with flowcharts, then moved on to pseudo code, and then, finally, implemented the pseudo code in any programming language of our choice. But in all this, the basic building blocks were the same. Actually, when we write any code in any programming language, the basic logic always remains the same; only the implementation of those basic building blocks in that particular language differs. For example, when we greet someone in English, we say "Hello" but the same in Hindi is "Namaste". So, the purpose of greeting remains the same and the effect is also the same. The only difference is that depending on the language and understanding, the words change.

Similarly, the building blocks of any logic can be categorized as follows:

  • Conditional logic
  • Conditional logic using loops

Now, let's take a look at how these two logics are implemented in PowerShell.

Conditional logic

In PowerShell, we have if, elseif, else and switch to use as conditional logic. Also, to use these logics properly, we need some comparison or logical operators. The comparison and logical operators available in PowerShell are as follows:

Comparison operators:

Operator

Description

-eq

Equal to

-ne

Not equal to

-lt

Less than

-gt

Greater than

-le

Less than or equal to

-gt

Greater than or equal to

Logical operators:

Operator

Description

-not

Logical Not or negate

!

Logical Not

-and

Logical AND

-or

Logical OR

The syntax for the if statement is as follows:

If (condition) { Script Block}
Elseif (condition) { Script Block}
Else { Script Block}

In the preceding statement, both elseif and else are optional. The "condition" is the logic that decides whether the "script block" will be executed or not. If the condition is true, then the script block is executed; otherwise, it is not. A simple example is as follows:

if ($a-gt$b) { Write-Host "$a is bigger than $b"}
elseif ($a-lt$b) { Write-Host "$a is less than $b"}
else { Write-Host " Both $a and $b are equal"}

The preceding example compares the two variables $a and $b and depending on their respective values, decides whether $a is greater than, less than, or equal to $b.

The syntax for the Switch statement in PowerShell is as follows:

Switch (value) {
Pattern 1 {Script Block}
Pattern 2 {Script Block}
Pattern n {Script Block}
Default   {Script Block}
}

If any one of the patterns matches the value, then the respective Script Block is executed. If none of them matches, then the Script Block respective for Default is executed.

The Switch statement is very useful for replacing long if {}, elseif {}, elseif {} or else {} blocks. Also, it is very useful for providing a selection of menu items.

One important point to note is that even if a match is found, the remaining patterns are still checked, and if any other pattern matches, then that script block is also executed. For examples of the Switch case and more details, check out https://technet.microsoft.com/en-us/library/ff730937.aspx.

Conditional logic using loops

In PowerShell, you have the following conditional logic loops:

  • do while
  • while
  • do until
  • for
  • Foreach
  • Foreach-Object

The syntax for do while is as follows:

do {
Script Block
}while (condition)

The syntax for the while loop is as follows:

While (condition) { Script Block}

The following example shows the preceding while loop. Say, we want to add the numbers 1 through 10.

The do while implementation is as follows:

$sum = 0
$i = 1
do {
$sum = $sum + $i
$i++
}while( $i –le 10)

$sum

The while implementation is as follows

$sum = 0
$i = 1

while($i -le 10)
{
    $sum = $sum + $i
    $i++
}
$sum

In both the preceding cases, the script block is executed until the condition is true. The main difference is that, in the case of do while, the script block is executed at least once whether the condition is true or false, as the script block is executed first and then the condition is checked. In the case of the while loop, the condition is checked first and then the script block is executed only if the condition is true.

The syntax for the do until loop is as follows:

do {
Script Block
}until (condition)

The main difference between do until and the preceding two statements is that, logically, do until is the opposite of do while. This is the script block is that is run until the time the condition is false. The moment it becomes true, the loop is terminated.

The syntax for the for loop is as follows:

for (initialization; condition; repeat)
{code block}

The typical use case of a for loop is when you want to run a loop a specified number of times. To write the preceding example in a for loop, we will write it in the following manner:

For($i=0, $sum=0; $i –le 10; $i++)
{
$sum = $sum + $i
}
$sum

The syntax for the foreach loop is as follows:

foreach ($<item> in $<collection>)
{code block}

The purpose of the foreach statement is to step through (iterate) a series of values in a collection of items. Note the following example. Here, we are adding each number from 1 to 10 using the foreach loop:

# Initialize the variable $sum
$sum = 0
# foreach statement starts
foreach ($i in 1..10)
{
# Adding value of variable $i to the total $sum
    $sum = $sum + $i
} # foreach loop ends
# showing the value of variable $sum
$sum

Logically, foreach and Foreach-Object do similar tasks, and sometimes this can create confusion between the two. Both of them are used to iterate through collections and perform an action against each item in the collection. In fact, foreach is an alias for Foreach-Object.

Conditional logic using loops

The difference between Foreach and Foreach-object

When we use Foreach in the middle of a pipeline, that is, when we pipe into Foreach, it is used as an alias for Foreach-Object, but when used at the beginning of the line, it is used as a PowerShell statement.

Also, the main difference between foreach and Foreach-Object is that when Foreach-Object is used, it executes the statement body as soon as the object is created, but when foreach is used, all the objects are collected first and then the statement body is executed.

So, when we are using foreach, we need to make sure that there is enough memory space available to hold all the objects.

Having said that due to optimizations in foreach, foreach will run much faster than the Foreach-Object statement, so the decision again boils down to that age-old question of performance versus space.

So, depending on the program that you are writing, you need to choose wisely between these two.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image