Reader small image

You're reading from  Mastering Windows PowerShell Scripting (Second Edition) - Second Edition

Product typeBook
Published inOct 2017
PublisherPackt
ISBN-139781787126305
Edition2nd Edition
Right arrow
Author (1)
 Brenton J.W. Blawat
Brenton J.W. Blawat
author image
Brenton J.W. Blawat

Brenton Blawat has been a successful entrepreneur, strategic technical advisor, and engineer who has a passion for the procurement of technology in organizations. He is business-centric, while being technology-minded, and has had many years of experience bridging the gap between technical staff and decision makers in organizations. Brenton prides himself on his ability to effectively communicate to a diverse audience and provide strategic direction for small and large organizations alike. Throughout his career, he has worked for a multitude of Fortune 500 organizations, and specializes in delivery automation and workflow optimizations.
Read more about Brenton J.W. Blawat

Right arrow

Chapter 6. Variables, Arrays, and Hashtables

This chapter explores variables along with a detailed look at arrays and hashtables, as these have their own complexities.

A variable in a programming language allows you to assign a label to a piece of information or data. A variable can be used and reused in the console, script, function, or any other piece of code.

In this chapter, we are going to cover the following topics:

  • Naming and creating variables
  • Variable commands
  • Variable scope
  • Types and type conversion
  • Objects assigned to variables
  • Arrays
  • Hashtables
  • Lists, dictionaries, queues, and stacks

A variable may be of any .NET type or object instance. The variable may be a string ("Hello World"), an integer (42), a decimal (3.141), an array, a hashtable, a ScriptBlock, and so on. Everything a variable might hold is considered to be an object when used in PowerShell.

Naming and creating variables


Variables in PowerShell are preceded by the dollar symbol ($), for example:

$MyVariable

The name of a variable may contain numbers, letters, and underscores. For example, each of the following is a valid name:

$123 
$x 
$my_variable 
$variable 
$varIABle 
$Path_To_File

Variables are frequently written in either camel case or upper-camel case (also known as pascal case). PowerShell does not enforce any naming convention, nor does it exhibit a convention in any of the automatic variables. For example:

  • $myVariable is camel case
  • $MyVariable is upper-camel case or pascal case

I suggest making your variable names meaningful so that when you come and visit your script again after a long break, you can identify its purpose. I recommend choosing and maintaining a consistent style in your own code.

It is possible to use more complex variable names using the following notation:

${My Variable} 
${My-Variable}

The following notation, where a file path is written as the variable name...

Variable commands


A number of commands are available to interact with variables:

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

Clear-Variable

Clear-Variable removes the value from any existing variable. Clear-Variable does not remove the variable itself. For example, the following example calls Write-Host twice: the first time it writes the variable value; the second time it does not write anything:

PS> $temporaryValue = "Some-Value"
Write-Host $temporaryValue -ForegroundColor Green

Some-Value

PS> Clear-Variable temporaryValue
Write-Host $temporaryValue -ForegroundColor Green

Get-Variable

Get-Variable provides access to any variable that has been created in the current session as well as the default (automatic) variables created by PowerShell. For further information on automatic variables, see about_Automatic_Variables (Get-Help about_Automatic_Variables).

When using the *-Variable commands, the $ preceding the variable name is not considered part of the name.

Default...

Variable scope


Variables may be declared in a number of different scopes. The scopes are:

  • Local
  • Global
  • Private
  • Script
  • A numeric scope relative to the current scope

Note

More about scopes:The help document, About_Scopes (Get-Help about_Scopes), has more examples and detail.

By default, variables are placed in Local scope. Access to variables is hierarchical: a child (scopes created beneath a parent) can access variables created by the parent (or ancestors).

Local and Global scope

When creating a variable in the console (outside of functions or script blocks), the Local scope is Global. The Global scope can be accessed from inside a function (child) because it is a parent scope:

Remove-Variable thisValue -ErrorAction SilentlyContinue 
$Local:thisValue = "Some value" 
"From Local: $local:thisValue"          # Accessible 
"From Global: $global:thisValue"        # Accessible 
 
function Test-ThisScope { 
    "From Local: $local:thisValue"      # Does not exist 
    "From Global: $global:thisValue"    #...

Type and type conversion


Type conversion in PowerShell is used to switch between different types of a value. Types are written between square brackets, in which the type name must be a .NET type, or a class, or an enumeration, such as a string, an integer (Int32), a date (DateTime), and so on.

For example, a date may be changed to a string:

PS> [String](Get-Date)
10/27/2016 13:14:32

Or a string may be changed into a date:

PS> [DateTime]"01/01/2016"

01 January 2016 00:00:00

In a similar manner, variables may be given a fixed type. To assign a type to a variable, the following notation is used:

[String]$thisString = "some value" 
[Int]$thisNumber = 2 
[DateTime]$date = '01/01/2016' 

This adds an argument type converter attribute to the variable. The presence of this converter is visible using Get-Variable, although the resultant type is not:

PS> [String]$thisString = "some value"
(Get-Variable thisString).Attributes 

TransformNullOptionalParameters TypeId 
-----------------------------...

Objects assigned to variables


So far, we have explored one-off assignments of simple value types, and while these values are considered objects, they are still (reasonably) simple objects. Once created, variables holding simple values such as integers and strings can diverge without affecting one another.

That is, the numeric value assigned to each variable is independent after creation:

$i = $j = 5

Each of the following commands increases the value held in the variable i by creating a new integer object (based on the original object):

$i = $j = 5 
$i++ 
$i += 1 
$i = $i + 1

If each statement is executed in turn, the variable i will be 8 and the variable j will be 5.

When changing the value of a property on a more complex object, the change will be reflected in any variable referencing that object. Consider this example where we create a custom object and assign it to two variables:

$object1 = $object2 = [PSCustomObject]@{ 
    Name = 'First object'
 }

A change to a property on an object will be...

Arrays


An array contains a set of objects of the same type. Each entry in the array is called an element and each element has an index (position). Indexing in an array starts from 0.

Arrays are an important part of PowerShell. When the return from a command is assigned to a variable, an array will be the result if the command returns more than one object. For example, the following command will yield an array of objects:

$processes = Get-Process 

Note

Array type:In PowerShell, arrays are, by default, given the type System.Object[] (an array of objects where [] is used to signify that it is an array).

Note

Why System.Object? All object instances are derived from a .NET, type or class, and in .NET every object instance is derived from System.Object (including strings and integers). Therefore, an array of System.Object in PowerShell can hold just about anything.

Arrays in PowerShell (and .NET) are immutable, and the size is declared on creation and it cannot be changed. A new array must be created...

Hashtables


A hashtable is an associative array or an indexed array. Individual elements in the array are created with a unique key. Keys cannot be duplicated within the hashtable.

Hashtables are important in PowerShell. They are used to create custom objects, to pass parameters into commands, to create custom properties using Select-Object, and as the type for values assigned to parameter values of many different commands, and so on.

Note

For finding commands that use Hashtable as a parameter, we use the following:Get-Command -ParameterType Hashtable

This topic explores creating hashtables, selecting elements, enumerating all values in a hashtable, as well as adding and removing elements.

Creating a hashtable

An empty hashtable is created the same as the following:

$hashtable = @{}

A hashtable with a few objects looks the same as the following:

$hashtable = @{Key1 = "Value1"; Key2 = "Value2"}

Elements in a hashtable may be spread across multiple lines:

$hashtable = @{ 
    Key1 = "Value1" 
    Key2...

Lists, dictionaries, queues, and stacks


Arrays and hashtables are integral to PowerShell and being able to manipulate these is critical. If these simpler structures fail to provide an efficient means to work with a set of data, there are advanced alternatives.

The following .NET collections will be discussed:

  • System.Collections.Generic.List
  • System.Collections.Generic.Dictionary
  • System.Collections.Generic.Queue
  • System.Collections.Generic.Stack

Each of these collections has detailed documentation (for .NET) on MSDN:

https://msdn.microsoft.com/en-us/library/system.collections.generic(v=vs.110).aspx

Lists

A lists is the same as an array but with a larger set of features, such as the ability to add elements without copying two arrays into a new one. The generic list, using the .NET class, System.Collections.Generic.List, is shown next.

The ArrayList is often used in examples requiring advanced array manipulation in PowerShell. However, ArrayList is older (.NET 2.0), less efficient (it can use more memory...

Summary


Variables can be created to hold on to information that is to be reused in a function or a script. A variable may be a simple name, or loaded from a file.

The *-Variable commands are available to interact with variables beyond changing the value, such as setting a description, making a variable in a specific scope, or making a variable private.

A Variable scope affects how variables may be accessed. Variables are created in the Local scope by default.

<p>Arrays are sets of objects of the same type. Arrays are immutable, and the size of an array cannot change after creation. Adding or removing elements from an array requires the creation of a new array.

Hashtables are associative arrays. An element in a hashtable is accessed using a unique key.

Lists, stacks, queues, and dictionaries are advanced collections that may be used when a particular behavior is required or if they offer a desirable performance benefit.

In the Chapter 7, Branching and Looping, we will explore branching and...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Windows PowerShell Scripting (Second Edition) - Second Edition
Published in: Oct 2017Publisher: PacktISBN-13: 9781787126305
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.
undefined
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 €14.99/month. Cancel anytime

Author (1)

author image
Brenton J.W. Blawat

Brenton Blawat has been a successful entrepreneur, strategic technical advisor, and engineer who has a passion for the procurement of technology in organizations. He is business-centric, while being technology-minded, and has had many years of experience bridging the gap between technical staff and decision makers in organizations. Brenton prides himself on his ability to effectively communicate to a diverse audience and provide strategic direction for small and large organizations alike. Throughout his career, he has worked for a multitude of Fortune 500 organizations, and specializes in delivery automation and workflow optimizations.
Read more about Brenton J.W. Blawat