Uploaded by Isaac Carrillo

CIS121AH - Module 4

advertisement
Module 4 – Scripting Environments, Strings, and Variables
In this module, we are going to learn how to start to build simple scripts. We will first look at using a
helpful program called an Integrated Scripting Environment. This is an introduction and we will continue
to use them as the class continues. After that, we will look at using variables to store data that we can
use as many times as well like in our script.
PowerShell ISE
PowerShell ISE comes with Windows Powershell. You can find it in the Start Menu or if you have
Powershell pinned to your task bar, you can right click on it and select PowerShell ISE.
*PowerShell Core Note: PowerShell Core doesn’t come with PowerShell ISE. VS Code, discussed below, is
multiplatform and can be used to develop PowerShell Core scripts on other operating systems.
Start Menu
Task Bar
You can also access PowerShell ISE by right clicking on a PowerShell script (a file that ends in .ps1) and
clicking Edit. Windows will open PowerShell ISE and load the script into the text editor.
PowerShell ISE allows you to build scripts more easily. It allows you to put multiple lines together into a
script and then run them all at once, one after another. Here are some basics of PowerShell ISE.
PowerShell Menu Bar
New – Creates a blank, new text editor tab that can be used to create a new script.
Open File – Opens an existing file and displays it in the text editor tab
Save File – Save the currently selected text editor window to a file
Cut – Cuts the currently selected text (the original is removed and pasted to the new location)
(Greyed out until you select text)
Copy – Copies the currently selected text (Greyed out until you select text)
Paste – Enters any text that is current copied or cut
Clear Console Output – Clears the console output window that is directly below the text editor
Undo – Reverses any change you just made to the text
Redo – Reverses the last Undo action you performed (Greyed out until you use Undo)
Run Script – Runs the entire contents of the current text editor tab
Run Selection – Runs the currently selected text
Stop – Stops the execution of the script that is currently running (Greyed out unless a script is
running)
Text Editor Pane
The text editor is where you will do the majority of your work in PowerShell ISE. This is where you can
enter your commands, one after another. It has many features that work just like any other text editor
such as Notepad, Word, Notepad++, or Google Docs. You can enter text, highlight, copy, and paste. The
difference is that this editor understand PowerShell. It will suggest cmdlets to you as you type using a
feature called Intellisense. You can see that in action here. Notice that I only typed Get-S and it is
suggesting some cmdlets that I might want to use.
It works the same for parameters on cmdlets as well. Notice that after I typed Get-Service and typed a
dash -, Intellisense shows the parameters that are supported by the Get-Service cmdlet. Intellisene
provides a real time way to learn about what parameters various cmdlets support.
The text editor also supports syntax highlighting. As you type in your commands, the text will be
highlighted in different colors based on what type of entry it is (i.e. cmdlet, parameter, string variable,
keyword, etc.). You will learn to recognize syntax errors when the text doesn’t turn the correct color.
You will learn the subtle differences over time with continued use and practice. Below is an example of
various text in different colors.
Console Output Pane
Directly below the text editor, you will see a pane that looks like a PowerShell command console. This is
exactly what it is! PowerShell ISE will take the commands in the text editor and run them in this console
and you will be able to see all of the output that results. You can use the symbol that looks like a
squeegee to clear this pane at any time (on the menu bar). Here is an example that shows the text
editor and console output. You can see in the console that it shows the commands that are run and then
the resulting output.
PowerShell ISE has many other features such as Debugging. We will look at these more advanced
features later.
VS Code
Visual Studio (VS) Code is a modern, feature rich, cross platform offered by Microsoft that can be used
to develop in many different languages. VS Code currently supports Windows, Mac, and Linux. VS Code
must be downloaded and installed, you can access the installers here. https://code.visualstudio.com/
When you open VS Code, it will look similar to this. I have it running in Dark Mode. It may start in Light
Mode and the window background will be white instead of charcoal.
When you first install VS Code, you need to enable the PowerShell language extension. We can do this
by clicking on the Extensions icon on the left side.
Once you do that, you will be able to search the Extensions Marketplace.
We need to search for PowerShell. Enter PowerShell into the search box and it will automatically list all
extensions related to PowerShell. Click the green Install button on the PowerShell extension as shown
here.
It will then install and show you information about the PowerShell extension. Notice that the install
button is gone from the PowerShell extension item and has been replaced by a gear icon for accessing
the settings of the extension.
Once you have PowerShell added, we can start using VS Code. Go to File and select New file.
A new tab will created called Untitled-1
We need to save this new file as a PowerShell file so that VS Code knows to enable PowerShell features
when working with it. The easiest way to do that is to save the file as a PowerShell script, which is a file
with a .ps1 file extension. We can do that by going to File and selecting Save As.
Once we do that we need to name the file and select PowerShell as the File Type in the dropdown list.
Here, I saved the file as VSCode-Example.ps1. Once I do that, the text editor pane will have PowerShell
features enabled such as Intellisense (discussed above in PowerShell ISE). You will also see that the icon
in the tab changes to look like a PowerShell icon.
VS Code shows the Run and Run Selection icons on the top right side of the text editor pane. You can see
them circled here.
Clicking the Run button with my simple script here shows the output in the command console below.
This was just a basic introduction to using VS Code. We will discuss more advanced features in future
modules.
Escaping Characters in Strings
We often have to output text to the console to provide the user information. One challenge we may
have is with non-character text. For example, how do we write a new line to the screen? How do we
write a tab character to the screen? We cannot simply press the enter key between quotation marks. A
double quote may seem like an easy thing to display until you think about the fact that it is used to
contain the text. A string like this will not work.
“Michael “Air” Jordan”
To Powershell, this would look like a string Michael, a command Air, and a string Jordan. The same
problem occurs with any special characters. Most programming languages have solved these problems
by using escape characters. Escape characters are simply a combination of characters that represent a
single “special” character. In many programming languages, these characters are escaped by a
backslash \, but in Powershell, it is the back tick ` character that performs this function. The back tick is
the character above the tab key on the left side of the keyboard. It is on the same key as the tilde ~ and
is generally below the ESC key. Here is the same example with proper escape sequences so Powershell
will understand what we want and print it correctly.
“Michael `”Air`” Jordan”
Here is a list of the escape sequences in Powershell.
Sequence
`’
`”
`0
`a
`b
`f
`n
`r
`t
`v
Description
A single quote
A double quote
A null value
A system beep
Backspace key
Form Feed
New Line (Next line)
Carriage Return (Beginning of the current line)
Horizontal Tab
Vertical Tab
Here is an example of using the newline character to write out a few lines of text using one command. I
assign the string to the variable $myString (we are covering variables later in this lesson) and then
display it.
The most frequently used escape sequences are probably `n, `t, `’, and `”.
Working with Strings
Strings are simply text data. We have been working with strings throughout the course. Every time we
typed some text contained within some double quotes we were specifying a string. Having a thorough
understanding of strings is important because we often have to manipulate text in our scripts. We will
look at three common operations: concatenation, repeating, and replacement.
String concatenation is the act of combing 2 strings. For example, if stringA is “Chad” and stringB is
“Galligan”, the result of concatenating them would be a string “ChadGalligan”. The string concatenation
operator in Powershell is the + symbol. So the correct Powershell statement for the example above is
“Chad” + “Galligan”
You can type this directly into the command prompt to see the results.
Right now, this may not seem that useful since we are only working with strings we type into the
console ourselves, but when we learn about variables and other functionality, the usefulness will
become apparent.
Another task we may need to perform is repeating text. We can use the * symbol. This is similar to
multiplication. For example, let’s say we need to print 20 spaces, we can to this.
“ “ * 20
Now simply printing this won’t be visible on the screen, so let’s put an A on each side to “bookend” the
spaces. We can use a combination of concatenation and repetition.
“A” + “ “ * 20 + “A”
We can do this with multi character strings as well. Here I will use an escape sequence to print Chad on
20 lines.
“Chad`n“ * 20
Another task we can perform on strings is replacement. This is similar to Find and Replace functionality
that exists in Notepad, Word, and other text editors. The syntax is as follows.
“string to search” –Replace “String to search for”, “String to replace it with”
You can see this in action here.
“A quick brown fox jumped over the fence” –Replace “quick”, “slow”
It is important to remember that –Replace is case-insensitive. If we need case sensitive matching, we
can use the –cReplace instead. In this example, you can see that the first command didn’t work since
the Q was capital in the word Quick. Since there were no matches, the string was returned without any
modification.
Splitting Strings
When we work with text, it is often necessary to split a string into pieces to extract individual items.
One very common format to store data in is a delimited text file. The word “delimited” simply means
data separated with a specific character or string. One example of this is comma delimited text. Here is
an example of comma delimited text.
Chad,Galligan,Associate Vice President/CIO, Estrella Mountain Community College
You can see that each data item is separated from the other items with a comma. Powershell provides a
–split operator that makes it simple to extract each data item from the string and use it separately.
The –split operator is used with a string that contains the delimited text and the specified delimiter. In
the example above, you can see I entered my comma delimited text and then specified the comma as
the separator. The separator can be anything.
In this example, I used the “s” character as the separator.
You can use multiple characters as well. In this example, I split the string based on “ll”.
Splitting a string in this way only has limited use. The real power is the ability to catch the values in a
variable and utilize them later. We can do that by assigning the result of the split operator to a variable.
The split operator returns an array of the values that result from the split.
The resulting elements can be accessed just like any other array element.
*Note: We will be discussing arrays in Module 5. For now, you only need to understand that they are a
collection of values
Joining strings to delimited text
In addition to splitting strings, there may be a time when we need to create delimited text. Powershell
provides a –join operator that does the opposite of –split. We take some string values (or an array of
strings) and specify the delimiter to use. Here are a few examples of using this.
In the example above, I take my 4 separate strings and create a single string with a semicolon used as
the delimiter.
In this example, we specify a string array and use the string “<br />” as the delimiter. If you know HTML,
you will recognize this string as the line break tag.
Variables
Except for a few examples, we have simply executed commands and viewed their results. When we
write scripts, we often need to store the results of commands to use later in the script. We use variables
to do this. Technically speaking, variables are a location in memory that are used to stored values.
Rather than reference the memory address, we assign an identifier that we use to reference that
location in memory. We can reference the identifier later to retrieve the value.
When we create a variable, we can give it any name we wish that starts with the dollar sign ($) symbol
and includes letters, numbers, and an underscore (_). We can create a variable simply by assigning a
value to one. We do this using the assignment operator (=). Here is an example of declaring and
assigning a variable called $myName.
$myName = “Chad Galligan”
We can view the contents of the variable by typing its name at the command line.
This variable can now be used anywhere we like. We can use string concatenation to put it in a
sentence.
“Welcome “ + $myName + “, how are you?”
We could also use double quotes to place the variable in the string and Powershell will parse the string
and replace the variable with its value.
This is not the case with single quotes. These quotes tell the Powershell that the value is a literal,
meaning exactly what is typed. Here we can see the difference.
Variables can be changed very easily. We just assign it a new value.
$myName = “Fred Flintstone”
Variables can hold more than strings. They can hold numbers, objects, and any other data type that
Powershell supports. Here are a few examples of that.
Numbers
Objects
You can see that variables can come in very handy to capture data for later use. We will discuss more
tasks we can perform below using various operators to act upon the data stored in variables.
Expressions and Operators
An operator is a special symbol that acts on two variables. That may sound complicated, but actually
simple math, comparisons, and other basic tasks are handled by operators. For example, arithmetic
operators are operators that perform math. Assignment operators assign values to variables. There are
a couple of other types of operators that we will discuss them in Module 6.
Arithmetic Operators
As the name implies, arithmetic operators perform simple arithmetic. They take two values and return a
result. Here is a table of the operators.
Operator
+
*
/
%
Description
Addition
Subtraction
Multiplication
Division
Modulus
All of operators probably look straight forward except the modulus. The modulus is simply the
remainder of a division operation. So 17 % 5 would equal 2, since the full answer would be 3 remainder
2. The 3 is ignored. Modular math can help solve all kinds of problems and is quite commonly used in
programming. A basic use is to find out if a number is odd or even. You simply do a modulus 2 and see
if the result is 0 (even) or 1 (odd). With a modulus you can also find the day of the week for any date
and modular math are even used with huge prime numbers to create public and private key pairs in
cryptography. Those tasks are beyond the scope of this class however.
You can type in these expressions at the command line to see their result. Here are examples of each
operation.
Addition
Subtraction
Multiplication
Division
Modulus
One thing we must keep in mind is the order of operations. If you remember way back to math class in
elementary school, there was a specific order that any operations were done in. You may remember
PEMDAS, which stood for Parenthesis, Exponent, Multiplication, Division, Addition, and Subtraction. If
this order is not followed, then the answer to the math problem would be incorrect. Computers must
follow the same order. We can use parenthesis to clarify the operations, just like in real world math.
Assignment Operators
The normal assignment operator (=) is what we have been using though most of this class to this point.
It simply assigns the value on the right side to the variable on the left side. Although many of the
examples we have seen are easy to understand, some may look incorrect at first, if you simply look at it
from a math standpoint. Take the following example.
Here, we assign the value 5 to the variable $myAns. Here is where it may seem confusing. The next
statement $myAns = $myAns + 2 might seem invalid. In the world of math, this would be an invalid
statement because 5 = 5 +2 is wrong. With the assignment operator, it is perfectly logical. Remember,
the equals sign is not saying that the two sides are equal. Rather, it is taking the result of the right side
and assigning it to the left side. So first, $myAns + 2 is evaluated. Since we previously set $myAns to 5,
5 + 2 = 7. We then take 7 and assign it to the variable $myAns, overwriting the old value of 5.
There are several other assignment operators that act as both an arithmetic operator and assignment
operator. Here is a table of those operators.
Operator
=
+=
-=
*=
/=
%=
Description
Assigns value
Increment operator
Decrement operator
Multiplies value of variable
Divides value of variable
Assigns the modulus of a variable
These may see unnecessary, since we have our arithmetic operators, we can already perform these
tasks. You are correct; we never have to use the 5 extra assignment operators if we choose not to. They
are simply shorthand. Rather than type this:
$myAns = $myAns + 3
We can type this
$myAns += 3
It is the same for all of the operators. We use them when we want to work with the already existing
value of the variable and perform some math on it.
The . (Dot) Operator
The dot operator (.) is used to access members of objects. Members are the properties and methods of
the object. At the command prompt, you can use tab completion to iterate through the members of an
object like you can iterate through the parameters of a cmdlet. In the following example, I get the
Powershell object that represents the C drive. I then display some of its properties and execute one of
its methods using the dot operator.
We will use the dot operator throughout the course. You will become very familiar using it to access
properties and methods of various types of objects.
Special Variables
Powershell creates some special variables that we can access. We can use these variables throughout
our scripts and at the command line.
Variable
$_
$Error
$Home
$PSHome
$null
Description
The current object in the pipeline
Errors that occurred
The current users home directory
The Powershell installation directory
Represents a null value
You can see these (except for $_ and $null) by typing them at the command line. $null is a special value
used in programming to represent no value. This is not the same as zero. It is nothing at all. If a
variable has not been assigned a value, then it is equal to $null.
Interacting with the User
Many time we will need to interact with the user during the execution of our script. This includes
displaying information and accepting information from the user. We use the Write-Host and Read-Host
cmdlets for this.
The Write-Host cmdlet is used to display text to the user. Its most simple usage is to just pass a string as
a parameter.
We can use the –foregroundcolor and –backgroundcolor to change the appearance of the output.
One problem that is common to new users of Write-Host is trying to concatenate strings in the same
statement. You can see how it may not behave as you expect.
There are two easy options to solve this. The first, is to simply concatenate the data before we write it.
The second option is to use double quotes and include the variables in the quoted string. Remember,
the contents of double quotes are examined and extrapolated before they are used.
Sometimes we must retrieve data from the user. The Read-Host simply returns the value entered.
If you thought that this example doesn’t look very useful, then you are correct. Most of the time, we
capture the output of the Read-Host cmdlet into a variable. Here is an example that is slightly more
useful.
The Read-Host cmdlet by itself simply waits for input and the enter key to be pressed. We can pass a
string that can be used to identify what information we need from the user to make it more user
friendly.
One important thing that we must mention about the Read-Host command, is that it reads input from
the user as a string by default. Generally, this is not a problem, but if we are asking the user to enter a
number value, it can cause issues because the variables will be treated like strings when we perform
operations on them. You can see this in the example below.
I prompted the user twice for values and stored them in two different variables. I then used the +
operator to add them together, but rather than return 10, PowerShell returned 55. Why did it do that
since 5 + 5 equals 10?
PowerShell returned 55 because it saw each 5 as a string value. The + operator will concatenate to
values if they are strings, which is why 55 was returned. If we want PowerShell to treat the value
returned from Read-Host as a number value and not a string, we need to explicitly tell PowerShell that
the variable is a number or integer. When talking about data, an integer is a whole number. We can
specify the datatype of our variables by placing [int] before the variable name on the line with the ReadHost command.
Now, you can see that the output of the $myInput + $myInput2 returns 10 rather than 55.
Download