[VMUG Session] PowerCLI 101 – PowerShell Basics

[VMUG Session] PowerCLI 101 – PowerShell Basics

Introduction

This is the first blog post of my guiding thread of my session for VMUG Austria meeting on 25th of April 2019. For second post about PowerCLI click here. I talked about:

  • PowerShell Basics (this post)
  • PowerCLI 101 (second post)
  • PowerCLI first function
  • Great PowerCLI open source project: vCheck

Some notes about the topics:

  • One of my goals was that every participant – no matter how experienced – should be able to get some new information.
  • Another goal is that attendees/readers wanna start to play with PowerShell.
  • This lecture should enable you to help yourself.
  • I concentrated on daily used structures (loops, variables, …).

Examples of usage

  • Single commands to get information or change settings
  • Reporting
  • Documentation
  • Automation
  • Poor man’s DRS
    • Use Host- and VM-groups to place VMs
  • Poor man’s vDS
    • VLAN management on virtual standard switches

Guiding principle

These are my personal principles about scripting

  1. PowerShell as Programming/scripting language –> with language you can say in another way what you just said –> most often there is no best-way to “say” something.
  2. Any working script is a good script!
  3. A good script is not working for everyone!

This is the power of programming/scripting: you can start with a working script and adapt it to work for your environment.

PowerShell  Basics

Variables

There are a lot of different types of variables: integer, double, character, string, … When working with vSphere objects, there are other types of variables as well. Lets start with simple integer and string:

$Number = 4
$String = "A few letters"

To show the content of a variable, just type in its name. To show type of variable, run for example:

$Number.GetType()

What about calculations.

4 + 9

Shows correctly 13. But

"4" + 9

doesn’t show an error but the result of 49 seems to be wrong. This is because “4” is interpreted as string. So “+” connects the two inputs to one string. This could happens when trying to calculate with variables and one of them is defined as string. To overcome this, use one of the following.

$a = "4"
$a/1 + 9

With “/1” PowerShell interprets $a as integer instead of string.

$a = "4"
[int]$a + 9

With prefix “[int]” PowerShell converts $a – just within this operation – to integer, if possible.

Array

Values can be organized in lists, such as an array. An array is a list of entries. For example all VMs of a cluster. To get to know arrays, we build an array containing numbers and an array containing letters.

$Numbers = 1..26
$Letters = [char[]](65..90)

Notes

  • Array index starts at 0.
  • “..” automatically fills in all numbers in between.
  • $Letters contains characters, not strings. This will be important later on.

To show an entry of an array, enter array-name followed by square bracket and entry number.

$Numbers[0]

To show all entries on screen sometimes it could be better to list them comma separated. You could do a small loop to do so, or you just run code like this:

$Text = $Letters -join ", "

Variable $Text now contains a string with all letters separated by commas. To do the other way round, run

$List = $Text -split ", "

To change an entry of an array you can use

$Letters = $Letters -replace "A","X"

To add an entry, run

$Letters += "a"

Hash Table

A hash table is like an indexed table in a database. You are able to get an entry of a hash table by entering the desired key.

To create an empty hash table run

$HashTable = @{}

To enter some entries run

$HashTable = @{File = "example.txt"; Path = "c:\temp"; Date = (get-date)}

To get an specific entry, run for example

$HashTable.path

or

$HashTable["path"]

and of course

$entry = "path"
$HashTable[$entry]

We will use this notation (“.”) later on. Normally it is used to get information of deeper level within the data structure. For another example look at the for-loop section.

Pipe

Pipe “|” is a very powerful feature of PowerShell. It is like pipe in Linux shell: the output of a command is the input of the next command. In Linux the input is text-based, here it is object-based. And this is a huge difference as we will see later on.

Loops

Another important concept of programming languages are loops. There are a few ways go through every element of lists. I will concentrate on three of them.

foreach – statement

Here is also our first use of pipe. With foreach, you go through every element by naming them during processing.

foreach ($Number in $Numbers) {$Letters[$Number -1]}

During processing the list of $Numbers, each element is placed into the variable $Number which can be accessed within curly brackets.

foreach-object

Our second loop is foreach-object. It is important to distinguish foreach statement from foreach-object as we will see later.
You can pipe a list of elements – like an array – into foreach-object. The cmdlet will go through every element. You have access to each element during the loop by querying the $_ variable. Here is a simple example.

$Numbers | ForEach-Object {$Letters[$_ -1]}

Attention
To demonstrate, foreach is not equal to foreach-object, see the following example.

$empty = ""
$empty | foreach-object {write-host "data"}
foreach ($a in $empty) {write-host "data"}

Each loop returns “data”. But when setting the list to $null, with means the variable is like never been used before.

$empty = $null
$empty | foreach-object {write-host "data"}
foreach ($a in $empty) {write-host "data"}

ForEach-Object returns “data”, foreach don’t.

for

This loop is a counter-based loop. In brackets is defined: index-variable and start-value; condition as long as loop runs; what happens to index after a loop-run.

for ($i = 1; $i -le 26; $i++) {Write-Host $Letters[$i -1]}

$i++ means to count 1 to $i.

With this loop we can easily create a hash table with our numbers and letters.

$LetterToNumber = @{}
for ($i=1; $i -le 26; $i++) {
     $LetterToNumber[($Letters[$i-1]).tostring() ] = $i
}

With this, we can “translate” a letter to its position within the alphabet. For example

$LetterToNumber.F

One response to “[VMUG Session] PowerCLI 101 – PowerShell Basics”

  1. […] This is the second part of the guide line of my VMUG session of PowerCLI 101. In first part I focused on PowerShell basics. […]

Leave a Reply

Your email address will not be published. Required fields are marked *