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:
$number=5
$letter="A"
$word="Hello"
$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.
$numbers=(1,2,3,4,5)
Write-Host "Here's
an array of numbers"
$numbers
$letters=("a","b","c","d","e")
Write-Host "Here's
an array of letters"
$letters
$words=("Hello","World")
Write-Host "Here's
an array of Words"
$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:
$b=("a",1,"Hello","World")
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:"
$States
Write-Host `n
Write-Host "Or
just pick one state, PA:"
$states.Item("Pennsylvania")
That’s all for this quick lesson. Next post we’ll talk about
some practical use of arrays and hashes.Labels: powershell