How to work with Variables, arrays, hash tables, and script blocks in Powershell



I have been recently working mostly on PowerShell /Azure, hence decided to covers lots of easier topics from this space. So that you can get familiar with this.
In the previous post, we looked into Credentials and how to use them while automating things.
In this post we are covering
·         Variables
·         Strict mode
·         Variable drives and cmdlets
·         Arrays
·         Hash tables
·         Script blocks



VARIABLES

Variables are a big part of any programming language or operating system shell, and PowerShell is no exception. In this post, we’ll explain what they are and how to use them, and we’ll cover some advanced variable-like data structures such as arrays, hash tables, and script blocks.


Variables are important for the creation of good scripts.

A variable is like a placeholder and every kind of object and type can be stored in that variable.

  1. You can save data that is often used within a script in it or you can make calculations with it.
  2. You can forward variables containing data to functions, to make changes or output with them.

Variables are the heart of every good script, cmdlet, function, and module.


In PowerShell, a variable name generally contains a mixture of letters, numbers, and the underscore character. You typically see variable names preceded by a dollar sign:


$varName = "NintyZeros.com" 



Variable Types

# varible stored as string
$varWithString = "Test"
$varWithString = 'Test'

#varibles stored as int
$varWithInt = 5

#get type of a variable
$varWithString.GetType()
$varWithInt.GetType()

#working with strings
$varCombined = $varWithString + $varWithInt
$varCombined #Test5

#additions
$calculatedVar = $varWithInt + 5
$calculatedVar #10 

Being strict with variables

PowerShell has another behavior that can make for difficult troubleshooting. For this example, you’re going to create a very small script and name it test.ps1. The following listing shows the script.




PS C:\Users\venka> $test = Read-Host "Enter a number"
Write-Host $tset
Enter a number: venkat


This kind of behavior, which doesn’t create an error when you try to access an uninitialized variable, can take hours to debug.




## Enabling the StrictMode 

Set-StrictMode -Version 1
$test = Read-Host "Enter a number"
Write-Host $tset


####################
Enter a number: venkat
The variable '$tset' cannot be retrieved because it has not been set.
At line:3 char:12
+ Write-Host $tset
+            ~~~~~
    + CategoryInfo          : InvalidOperation: (tset:String) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined 

ARRAYS

In many programming languages, there’s a definite difference between an array of values and a collection of objects.
In PowerShell, not so much. There’s technically a kind of difference, but PowerShell does a lot of voodoo that makes the differences hard to see.
Simply put, an array is a variable that contains more than one value. In PowerShell, all values—like integers or strings—are technically objects. So it’s more precise to say that an array can contain multiple objects. 
Arrays can be created from simple values by using the array operator (the @ symbol) and a comma-separated list:

Below examples will help you understand much better.


#fetch all the service running or atopped and stored in object
$services = Get-Service

#Filtering out only running services
$services | Where-Object Status -EQ "Running"

#Fetching based on Index 0 
$services[0]


#Create a array
$var = @('Car','Bike','Cycle')
write-host $var
$var[2]

#creating empty array and adding elements
$empvar = @()
$empvar+='car'
$empvar+='bike'
$empvar+='cycle'

write-host $empvar 

HASH TABLES AND ORDERED HASH TABLES

Hash tables (which you’ll also see called hash tables, associative arrays, or dictionaries) are a special kind of array.
These must be created using the @ operator, although they’re created within curly brackets rather than parentheses—and those brackets are also mandatory.
Within the brackets, you create one or more key-value pairs, separated by semicolons. The keys and values can be anything you like:


#Creating a simple hastable
$hasexp = @{
Name="NintyZeros";
Author= "Venkat";
};

##What is name of website ?
$hasexp.name

##What is the name of author?
$hasexp.Author

##adding an element to hashtable
$hasexp.Add("site","nintyzeros.com")

##Result
$hasexp.site

#Removing an element by key
$hasexp.Remove("site")
 
Ordered hash tables
One problem with hash tables is that the order of the elements isn’t preserved. Consider a simple hash table:

With PowerShell v3 and v4, you can create a hash table and preserve the order of the elements:


$hash1 = [ordered]@{
 first = 1;
 second = 2;
 third = 3
}
$hash1 


Script blocks

This we have just forced into this post 👏, but like variables, arrays, and hash tables, script blocks are a fundamental element in PowerShell scripting. They’re key to several common commands, too, and you’ve been using them already.


A script block is essentially any PowerShell command, or series of commands, contained within curly brackets, or {}. Anything in curly brackets is usually a script block of some kind, with the the sole exception of hash tables (which also use curly brackets in their structure).
A script block is a collection of statements and/or expressions.
In addition, it can be saved to variables, and even passed to functions or other language constructs:

{ 'This is a simple ScriptBlock'}

 Conclusion:
Variables are one of the core elements of PowerShell that you’ll find yourself using all of the time. 
They’re easy to work with, although some of the specific details and behaviors that we covered in this post represent some of the biggest “gotchas” that newcomers stumble into when they first start using the shell.
Hopefully, by knowing a bit more about them, you’ll avoid those pitfalls and be able to make better use of variables.

Alll the world is a laboratory to the inquiring mind! Join Us

Comments

Popular posts from this blog

Managing CSV Files using Import/Export-CSV in Powershell

Android Navigation Drawer sliding menu with fragments

How to work with PowerShell Files Read/Write using Set-Content & Get-Content