Intro to PowerShell - Variables

PowerShell is an amazing tool that can save you copious amounts of time in your day to day working life. I’ve found that a lot of admins just don’t know the basics, they can take a command and change the names to match their environment but that’s the extent of their abilities. With just a little knowledge you can get started taking things you find on the internet and not just changing them to fit your network but to use them as starting points to develop your own tool set.

Let’s face it, if you are a tool maker you’re in demand!

This will be the first of a set of posts that will walk you through some of the basic concepts in PowerShell and then expand on these concepts to tasks around a system administrator’s daily life.

Variables in PowerShell come in three simple types. A variable can be either a scalar, array, or hash. In their most basic forms they can be explained as a single piece of data, a list or index of data (sometimes called a “collection”), and a hash (also called a “dictionary”). Today we will go over the different variable types a simple examples of each.

 A scalar variable is the simplest type of variable, it is just a piece of data. A scalar can be a number, a string of numbers, a piece of text, etc. You set up a scalar by simply setting a variable with a value. A couple quick examples are:
$text="Hello World"
Write-Host "This variable is a....."
Write-Host "Number:" $number
Write-Host "Letter:" $letter
Write-Host "Word:" $word
Write-Host "Text:" $text

An array is the next type of variable we use. It is basically an ordered list of values. You can push values into and read specific values from it. You can loop through it or select specific values, such as grabbing the first, last, or fifth value.

Write-Host "Here's an array of numbers"
Write-Host "Here's an array of letters"
Write-Host "Here's an array of Words"

To loop through an array by using a simple foreach loop or to pick specific elements of an array you can do the following:
Write-Host "Loop through an array with a Foreach command:"
foreach ($a in $b) {
    Write-Host $a
Write-Host `n
Write-Host "You can also pick a specific element of an array (starting at 0)"
Write-Host "Letter:" $b[0]
Write-Host "Number:" $b[1]
Write-Host "Words:" $b[2] "," $b[3]

A hash is where you get to set up pairs of information, so a definition or KEY and the value. One of the common examples is matching states with their capitals.

$States=@{"Pennsylvania"="Harrisburg";"New Jersey"="Trenton";"New York"="Albany";"Deleware"="Dover";"Maryland"="Annapolis"}
Write-Host "A colleciion of states and their capitals:"
Write-Host `n
Write-Host "Or just pick one state, PA:"

That’s all for this quick lesson. Next post we’ll talk about some practical use of arrays and hashes.