You are on page 1of 45

Scripting

Week 3 Topics
Nirmal Anam
Matthew Cubis

Topics
Detour to Additional Features of Powershell
Reserved Words (Slide 3)
Escape Characters (Slide 5)
String Manipulation (Slide 7)
Storing and Retrieving Data
Variables (Slide 11)
Arithmetic operators (Slide 13)
Assignment operators (Slide 21)
Arrays (Slide 26)
Hashes (Slide 30)
Using Single Quotes and Double Quotes (Slide 32)
Data Types (Slide 38)

Detour to Additional Features of PowershellReserved Words


Reserved Word (Keyword) Words which have a
special purpose or special meaning in the language
(powershell) and are hence not available for use as
variables, array, associative array and function
names. They should be used according to strict
syntactical rules.
For more info: get-help about_reserved_words

Detour to Additional Features of PowershellReserved Words

Detour to Additional Features of PowershellEscape Characters


These characters are identified by ` key (button on
top of tab on the keyboard). They have a special
meaning and provide convenience and control over
text output by letting script writers do things like
inserting newline feeds or tabs at any point within
text string.
For more info: get-help about_escape_characters

Detour to Additional Features of PowershellEscape Characters

Detour to Additional Features of PowershellString Manipulation


A number of string manipulation techniques are available in
Powershell such as Concatenation, Repeating Character Strings,
Replacing Parts of a string, Splitting and Joining Strings.
Concatenating: We can join two strings into one by using the += or
+ operator as follows.

Detour to Additional Features of PowershellString Manipulation


Repeating character strings: This can be used to display
headings (or borders).

Detour to Additional Features of PowershellString Manipulation


Replacing a String: We can use replace operator to
replace any part of the string by specifying the string
followed by the string operator and the two
arguments (string to be replaced, string to be
replaced with).

Detour to Additional Features of PowershellString Manipulation


Splitting and joining a string: We can join a string by using
join operator and split a string by using split operator. In
either case we can provide or not provide a delimiter.

Storing and Retrieving Data


Although, We can execute cmdlets and manipulate
data, pass it from one object to another through
object pipeline there are some limits. To overcome
this to be able to manipulate data and have the
flexibility to also store and retrieve data we can use:
Variables Store individual piece of data
Arrays Store data as index list
Hashes Store data in key-value pairs.

Storing and Retrieving Data - Variables


Using variables we can store data (numbers, strings and objects) within
powershell scipts. When objects are stored from an output by a cmdlet,
powershell is conscious of the object types and hence can retain the
properties and methods associated with the object as well.
While naming a variable remember that:
It needs to start with a $
It can have characters, numbers and underscore _ character.
No blank spaces or other special characters like (#@ etc unless used
with {}.
${good#!} = Winner
Variable names are not case sensitive.
If a variable name is invalid the script will terminate and display an error.

Storing and Retrieving Data Arithmetic


Operators
Other Powershell Arithmetic Operators: (Two operators +
and * are overloaded, allowing them to work for both strings
and numbers concatenation and repetition of strings)

Storing and Retrieving Data Arithmetic


Operators
Precedence:
Mathematic operations are performed in a specific order
of precedence which occurs from left to right basis.
unary operator which negates a number is evaluated
first.
Next powershell performs multiplication and division and
then remaindering. Finally addition and subtraction are
performed.
Example: $a = 10 * 2 / 2 * 5 5 * 2

Storing and Retrieving Data Arithmetic


Operators
Precedence:
Mathematic operations are performed in a specific order
of precedence which occurs from left to right basis.
unary operator which negates a number is evaluated
first.
Next powershell performs multiplication and division and
then remaindering. Finally addition and subtraction are
performed.
Example: $a = 10 * 2 / 2 * 5 5 * 2 =

Storing and Retrieving Data Arithmetic


Operators
Precedence:
Mathematic operations are performed in a specific order
of precedence which occurs from left to right basis.
unary operator which negates a number is evaluated
first.
Next powershell performs multiplication and division and
then remaindering. Finally addition and subtraction are
performed.
Example: $a = 10 * 2 / 2 * 5 5 * 2 = 40

Storing and Retrieving Data Arithmetic


Operators
Precedence:
Mathematic operations are performed in a specific order
of precedence which occurs from left to right basis.
unary operator which negates a number is evaluated
first.
Next powershell performs multiplication and division and
then remaindering. Finally addition and subtraction are
performed.
Example: $a = 10 * 2 / 2 * 5 5 * 2 = 40
Parenthesis can be used for clarity: $a = (10 * 2 / 2 * 5) (5
* 2) =

Storing and Retrieving Data Arithmetic


Operators
Precedence:
Mathematic operations are performed in a specific order
of precedence which occurs from left to right basis.
unary operator which negates a number is evaluated
first.
Next powershell performs multiplication and division and
then remaindering. Finally addition and subtraction are
performed.
Example: $a = 10 * 2 / 2 * 5 5 * 2 = 40
Parenthesis can be used for clarity: $a = (10 * 2 / 2 * 5) (5
* 2) = 40

Storing and Retrieving Data Arithmetic


Operators
Precedence:
Mathematic operations are performed in a specific order of
precedence which occurs from left to right basis.
unary operator which negates a number is evaluated first.
Next powershell performs multiplication and division and then
remaindering. Finally addition and subtraction are performed.
Example: $a = 10 * 2 / 2 * 5 5 * 2 = 40

Parenthesis can be used for clarity: $a = (10 * 2 / 2 * 5) (5 * 2) = 40


Parenthesis can also be used for changing the order of execution of
the expression: $a = 10 * 2 /( 2 * 5 5) * 2 =

Storing and Retrieving Data Arithmetic


Operators
Precedence:
Mathematic operations are performed in a specific order of
precedence which occurs from left to right basis.
unary operator which negates a number is evaluated first.
Next powershell performs multiplication and division and then
remaindering. Finally addition and subtraction are performed.
Example: $a = 10 * 2 / 2 * 5 5 * 2 = 40

Parenthesis can be used for clarity: $a = (10 * 2 / 2 * 5) (5 * 2) = 40


Parenthesis can also be used for changing the order of execution of
the expression: $a = 10 * 2 /( 2 * 5 5) * 2 = 8

Storing and Retrieving Data Assignment


Operators
In addition to using = operator there are other operators
available for assigning purposes. For example:
$a = 3
$a += 2
$a will now be 5.
In addition we can use ++ or to automatically increment or
decrement a value by 1. For example: $x = 5
$x = 5
$y = $x++
Now $ y = 5.
$X will be 6.

Storing and Retrieving Data Assignment


Operators

Storing and Retrieving Data Special


variables
Windows provides access to number of variables that
are available in powershell scripts and have access to
commonly used information. Understanding and
using these variables often saves time rather than
having to create new ones.
Set-location $home
$x = Get-ChildItem
$x
For more info: get-help about_automatic_variables

Storing and Retrieving Data Special


variables

Storing and Retrieving Data Variable Scope


Where can you access a variable depends on where you define a variable.
This is referred to as the scope. There are 4 scopes supported by
powershell:
Local Scope : Current scope which can be global, private or script
Global Scope: Scope that is established when new powershell session
is started.
Private Scope: Scope that is not visible or accessible to other scopes
Script scope: Scope that is established whenever a script is executed
and ends when script stops executing.
We will come back to this concept of variable scope after covering the
programming concepts for the powershell scripting language.

Storing and Retrieving Data Arrays


An array is an indexed list of values. Each element
stored in an array is assigned a unique numeric index
number, which can later be used to retrieve its value.
In Windows PowerShell, array indexes start at zero,
so the first element in an array has an index of 0, the
second element has an index of 1, and so on.

Storing and Retrieving Data Arrays


Creating an Array: You can create a new empty array by assigning a
comma-separated list of values to a variable, as demonstrated here:
$names = Alexander, William, Molly
Once its created, you can refer to any array element by referencing its
index number:
Write-Host $names[2] is a great kid.
Windows powershell allows you to use negative numbers to reference the
elements stored in an array. So index value of -1 would refer to last
element in the array and -2 represents the second last element.
If you create an array made up of numeric data, as demonstrated here,
you can omit enclosing array elements inside matching quotations marks.
$numbers = @(1, 2, 3, 4, 5)
Write-Host $numbers

Storing and Retrieving Data Arrays


Range Operator (..) can be used to enter a range of values into an array.
$numbers = @(1..10)
Modify an element by specifying index number.
$numbers [2] = 9
$numbers
Arrays have a count property and length property that tell the number of
elements in an array:
$c = $numbers.count
$c = $numbers.length
Combine arrays to form larger arrary. Example: $d = $a + $b where $a is
array with values 1, 2, 3 and $b is array with values 4, 5, 6. Now $d will be
an array with values 1,2,3,4,5,6

Storing and Retrieving Data Arrays


No direct way to insert or delete an element in an
array.
Delete an element :
$numbers = @(1,2,3,4,5,6,7)
$numbers = $numbers[0..2 + 4..6]
$numbers
Insert an element:
$numbers = @(1,2,3,4,5,6,7)
$numbers = $numbers[0..3] + 99 + numbers[4..6]
$numbers

Associative Arrays [Hash or Dictionary]

Large arrays become hard to manage (searching through each element is tedious).
Associative arrays also referred to as Hash or Dictionary, allows us to store data
in key-value pairs.

You can assign values from hashes into other variables: $y = $x[345]
Keys and values can be of any length. Amount of time to retrieve data is fast and
doesnt increase even with more values.
Associative arrays can be combined too: $y = $x + $superhero

Associative Arrays [Hash or Dictionary]


We can remove an entry in an associative array by:
$y.Remove(345)
$y
We can clear contents of an associative array by:
$y.clear()
For more information on associative arrays
Get-Help about_Hash_Tables

Using Single Quotes and Double


Quotes
There is a difference in the way powershell deals
with data in single quotes compared to double
quotes.
Variables within are interpreted by powershell
and substituted with their actual value where as the
variables in are not interpreted.

Using Single Quotes and Double


Quotes
Example:

Using Single Quotes and Double


Quotes
In the previous slide, the first write-host output
interpreted $x as 4 because we used double quotes
to enclose the text
The second Write-host gave $x as it is
In the third Write-host we could see that the first $X
was not interpreted but the second $x was
interpreted to value 4. This is because we used the
backtick just in front of $X. We can use this backtick
for other reasons like the ones we saw in the escape
characters section

Using Single Quotes and Double


Quotes
The variables inside double quotes will be
interpreted in other cases too like below:

Using Single Quotes and Double


Quotes
In the previous example we could see that $x was
stored in $y as $x when we used single quote, but
the value of $x which is 4 was stored in $y when we
used double quotes.

Using Single Quotes and Double


Quotes
The same concept also applies while working with
arrays.

Data Types
Powershell variables can contain various types of
values.
For Example:
$x = 2 (we are storing a number, so it is of the type
Integer, referred in powershell as int32
$x = Hello (Here we are storing a text value, it is
of type string, referred in powershell as string)
There are a number of data types a variable can
have.

Data Types
Powershell variables can contain various types of values.
For Example:
$x = 2 (we are storing a number, so it is of the type Integer,
referred in powershell as int32
$x = Hello (Here we are storing a text value, it is of type
string, referred in powershell as string)
There are a number of data types a variable can have.
Generally powershell accepts a value of any data type to be
stored in a variable. But sometimes there could be a situation
where you want to force a variable to accept a value of a
certain data type. Example is given in the next slide.

Data Types
By default read-host accepts and stores a value as string which
sometimes wont be suitable for our purpose:

Both times 12 is stored as text (default data type while using readhost). We know that the + operator combines two text values just
like combining two words.

Data Types
We can force $X and $y to store values as numbers and not text:

By placing [int] before $x and $y we have got the values stored as


numbers. Once we use [int] before the variable $x we dont have to use
[int] again as $x will remember this for further use.
We can change the data type to something else later. For example,
[string]$x = Hello after the above code will make $x accept text values.

Data Types
Other types of commonly used data types for
variables are:
[Int] : Integer numbers
[string] Text or string of characters
[single] and [double] : floating point numbers
(numbers with decimal portion)
[char] : Exactly one character
[xml] : An xml document

Task 1 (DIY)
This task will be based on all the concepts
learnt in this week Variables, Arrays, Hashes,
Operators, Escape Characters, String
manipulation.

Conclusion
Objective
By the end of this section you should understand
the usage of variables, arrays, hashes clearly. You
should have an understanding on how to use the
various types of operators and data manipulation
techniques including escape characters and the
difference between using single and double
quotes.

References
Learn Windows Powershell 3 in a month of
lunches, second edition by Don Jones and
Jeffery Hicks
Microsoft Windows Powershell Programming
for the absolute beginner, third edition by
Jerry Lee Ford Jr.

You might also like