Sunteți pe pagina 1din 30

9/1/2015 Variables 1

INTRODUCTION TO SCRIPTING
AND POWERSHELL

Win213

Lecture 3 - Scripting Basics I / Working with Variables


(Photos and icons used in this slide show are licensed under CC BY-SA)
9/1/2015 Variables 2

Agenda
Why Create Scripts?
• Purpose
• Scripting vs Compiled Programming Languages
• Essentials (basics) of Programming: (variables and control flow statements)
• Windows commands as aliases

Variables
• Purpose
• Types of Variables (Automatic, Environment, User-defined)
• Variable Naming Rules
• Un-Types vs Strongly-Typed User-Defined Variables
• Creating, Testing and Deleting Variables

Writing Scripts to Manage Windows Server


• Working with Get-Help (updating, CLI / GUI, Using Get-Help)
• Instructor Demonstration: Application of Lesson to a PowerShell Script
9/1/2015 Variables 3

Why Create Scripts?


In the previous slides, we have discussed how to use the
PowerShell ISE, as well as teaching your how to create,
run, and debug PowerShell scripts.

We haven’t taken the time to explain the reason why it is


your best interest (as a future IT professional) to learn how
to create and use PowerShell scripts:

Learning how to configure a computer graphically


(regardless of the operating system) is useful, but it is NOT
practical when administering (managing) large computer
networks.

Know how to write scripts will help you to automate tasks


on local and remote servers (without you being present).
You will learn fast that the scripts you create are re-usable.
9/1/2015 Variables 4

Why Create Scripts?


Are PowerShell scripts considered a programming language?
Answer: YES

PowerShell (Windows) and Bash Shell (UNIX/BSD/Linux) scripts


are file(s) that contain instructions to be run in a sequence in order to
complete a task or a set of tasks.

They are stored in files for they can be run manually, or can be
scheduled to run automatically at a certain time on a period basis
(so the IT administrator can perform other tasks or SLEEP!)

What type of instructions?!?


Answer: Depends on the OS and the scripting language. The
instructions could be operating system commands, or
in our case: cmdlets, function names, program names, etc…
9/1/2015 Variables 5

Scripts vs Compiled Programs


Digital Computers has evolved over a long period of time
(approx. 80 years). As the computer hardware has evolved, the
programs that instruct the computer what to do, and the
programs to allow users to complete a task have evolved as
well…

Although there are many programming languages that have been


created, they are basically grouped into 2 general categories:
Scripting Languages
Commands, cmdlets, functions, etc. are placed into a file, and
when files is run a shell interprets (e.g. reads command, and then
tries to run the command – this is done in sequence).

Compiled Languages
Programmers use a set of instructions that they find easy to
understand (source code), then compile (transform) the source
code into an executable file. This executable file is in machine
language which will run fast and is understood by the computer.
9/1/2015 Variables 6

Scripts vs Compiled Programs


Which one is better scripts of compiled programs?
Answer: It is not necessarily which one is better, but
which one would be most suitable to use for
a given task to solve (i.e. “best tool for the job”)
For Example:

Compiled programs run more efficiently than scripts (interrupted


programs), but it could take longer to create a compiled program,
and if it doesn’t compile, you cannot run it.
Scripts are usually designed to run periodically or occasionally
(like managing a Server) as opposed to
compiled program designed to by run by many users at the same
time.
IT professionals learn which programming language to use from
experience. PowerShell is a good “tool” for this course since
we will create scripts to manage our servers on a periodic basis,
and since it is “object-oriented” which makes it easier to
manipulate our Windows server.
9/1/2015 Variables 7

Essentials of Programming
When gaining experience over time as an IT professional you
may learn several different programming languages to help to
help automate a task or a group of tasks.

Although each different programming language may have


different syntax rules and ways to “doing things”, after a while,
you begin to see a common pattern that is common to all
programming languages:

• They exist to solve a problem.


• They contain OS commands and/or programming function-calls.
• They allow for creating a using variables.
• They contain special statements (logic & loops), that when
combined with variables, allow the program to
run differently under different situations.
• Programs can be recycled and used in other programs
(eg. Program names, function names, development libraries)
9/1/2015 Variables 8

Windows Commands as Aliases


When you were taught Bash shell scripting in ULI101, you learned that
scripts contained Linux operating system commands as well as
other reserved words for logic and loops.

Since PowerShell supports aliases, this gives the “illusion” that you are
running Windows commands in your scripts, which are actually aliases
or “nicknames” for cmdlets.

In order to see how a Windows commands is associated with a


PowerShell alias, you can issue the cmdlet:

Get-Alias
Get-Alias Windows-Command

Although you can issue windows commands in your script, by using


the Get-Alias cmdlet, you can determine which PowerShell cmdlet to
use. In some cases, the PS cmdlet may offer more features…
9/1/2015 Variables 9

Variables
A program would be very boring if it always did the same
predictable thing over and over, although very boring could be
useful like backing up all the VMs on your computer system.

But what if we added new VMs on our system?


How would our program adapt to that new situation?

We designed programs have the ability to adapt and run


differently under different situations. You should have learned
in ULI101 that you can use logic and looping statements to
change how that script behaves (which “direction” or sequence
it will take).

Variables help program developers (in our case, “scripters”) to


store data that can be used throughout a script and allow the
sequence of how the script runs to change under different
situations.
9/1/2015 Variables 10

Variables
The simple name “variable” indicates that it has the ability for change.

One way to think of variables is a storage container that contains a single


piece of data that is stored in the computer’s internal memory (RAM). We
can somehow put that data into the container (give it a name), and are able
to use it in our script to change the outcome of the action that is takes (you
should have seen this when creating Bash shell scripts in your ULI101
course).

Think about how the word “variable” is used in our language:

• A variable weather pattern


• Variable stock market prices
• Variable items to select at our store

There is a neat type of variable (storage container) called Arrays that can
store multiple sets of data at the same time and is very useful, but we will
wait until week 6 to discuss…
9/1/2015 Variables 11

Variable Types
The data that variables contain can represent:
• Results from commands
• File or Directory Pathnames
• Usernames (account names)
• System setting information
• Etc…

Some variables assign data values are already assigned by the


operating system when PowerShell loads or show status of
previous commands, etc and cannot be changed
(automatic variables), other variables store system information
which may or may not be changed (environment variables), while
other variables can be created by the author of a script
(user-defined variables).
9/1/2015 Variables 12

Variable Type: Automatic Variables


Purpose:

• Assigned by PowerShell when starting-up

• Not allowed to change the variables name and value.

• Created with each PowerShell session, used to store important


system information such as paths and user settings.

• Are stored on the variable and env drives, as well as the internal
system.

• Stores the installation path to PowerShell executable:


PowerShell.exe and PowerShell_ISE.exe

• All PowerShell versions are stored in a subfolder called: V1.0


9/1/2015 Variables 13

Variable Type: Automatic Variables


Purpose:

There is a similarity to read-only shell variables (and positional parameters)


in Bash shell scripts
Some other useful automatic variables include:

$? - Contains the execution status of the last operation. It contains TRUE if


the last operation succeeded and FALSE if it failed.

$ARGS - Contains an array of the undeclared parameters and/or parameter


values that are passed to a function, script, or script block (discussed later
in this course).
$PSVERSIONTABLE - Contains a read-only hash table that displays
details about the version of PowerShell that is running in the current
session.

$PSHOME - Contains the full path of the installation directory for


PowerShell

$HOME - Contains the full path of the user's home directory.


$PWD - Contains a path object that represents the full path of the current
directory.
9/1/2015 Variables 14

Variable Type: Environment Variables


Purpose:
• Created by system or user

• Allowed to change the name and value.


NOTE: Be very careful when adding\changing environment variables, they
are used by OS and running applications.

• Ends when session ends

• Can add a directory path to a profile to make permanent

Example: Adding a directory pathname to PATH environment variable

Environment variable: $Env:Path


(use current path value or add new directory paths to Path variable)
e.g. $env:path = $env:path + “;$HOME\Documents\PowerShell2”

NOTE: Adding folder PowerShell2 to the path means that you don’t need to
explicitly type “.\” to run executables. PowerShell now trusts the source because it
is on the “path”.
9/1/2015 Variables 15

Variable Type: User-Defined Variables


Purpose:
• Created by user

• Allowed to change the variable name and value

• End when session ends

• Can by added to profile to make permanent

Examples:
User-defined variable: $DisplayName , $Program
(i.e. created in script for lab2)
9/1/2015 Variables 16

Variable Type: User-Defined Variables


Variable Naming Rules:
• Are case insensitive (can be UPPERCASE and lowercase).

• Avoid short cryptic names, use full word(s) for description.

• Use CamelCase notation: e.g. CustomerShoeSize (easier to read)

• Avoid using prohibitive (special) characters or PowerShell key words


for a variable name.

• Avoid creating variables that use existing Environment variables.

• All types of names are allowed if enclosed in braces


(but use “common-sense”).
9/1/2015 Variables 17

Variable Type: User-Defined Variables


Un-Typed vs Strongly-Typed Variables:
• In Bash shell scripting, all variables store data as strings (text). In the
scripting section of lab2 for your OPS235 course, it will mention that you
need to use “tricks” to convert those variables (stored as text) into binary
numbers to be able to perform math operations.

• PowerShell is a newer language and makes it easier for the PowerShell


interpreter to determine what type of data is stored into a variable.

• PowerShell has the ability to use Un-Typed as well a Strongly-Typed


variables. These features may be confused as the same thing, but knowing
the different between these terms will help you to properly create and use
variables in your script.
9/1/2015 Variables 18

Variable Type: User-Defined Variables


Un-Typed Variables:
• When you were creating a script for lab2 to prompt and display a person’s name and
program ($DisplayName, $Program), you were using untyped variables.

• Un-Typed variables can store any type of data (e.g. numbers or strings of text), and the
type of data could change at any time when the variable is used.

• When using Un-Typed variables, the PowerShell interpreter determines (guesses) what
the data is when the variable is used in the script (e.g. text, or a number in order to
perform a mathematical calculation).

• Using quotes around values (single or double) denote a string.

• For Example:
$var=“Murray Saul”
$num=123
9/1/2015 Variables 19

Variable Type: User-Defined Variables


Strongly-Typed Variables:
• There are situations when you do NOT want the variable to store different
data types as they are used throughout the script.

• The author of the PowerShell script wants to control what the data-type of
the variable, as opposed to the PS interpreter accepting any data to be
contained in the variable.

• For example, you may want the variable to only store numbers as opposed to
strings of text. Error checking to prevent incorrect data from being entered
from users is mandatory for creating excellent shell scripts.

• In that case, you would need to declare the data-type of the variable, either
prior-to or during the assigning a value to the variable.
9/1/2015 Variables 20

Variable Type: User-Defined Variables


Strongly-Typed Variables:

Here are some examples of declaring the


data-type of a variable during assigning a Common Data Types
value: Data Type Description
[int] 32 bit signed integer
[double] $Number1 = 10.5
[long] 64 bit signed integer
[int] $Number2 = 123
[decimal] 96 bit floating point number
[bool] $decision = true (more precise than double)
[string] $FullName = “Mohammed” [double] Double-precision 64-bit floating point number
[single] Single-precision 32-bit floating point number
Common variable data-types are displayed [bool] Boolean true or false value
in the chart to the right. [string] Fixed-length string of Unicode characters
[DateTime] Date and Time object
9/1/2015 Variables 21

Variable Type: User-Defined Variables


Declaring New Variables:
By creating (declaring) a new variable prior to use, you can set attributes for the
variable which can sometimes be useful. You use the New-Variable cmdlet to do this.

An excellent example would be to create a variable with a value, but also set it to be
read-only, so it cannot be changed when the script is running (known as a “constant” in
programming languages).

New-Variable –Name TaxRate –Value 0.13 –Option Readonly

See what happens below when you try to change the value of the readonly
variable.
9/1/2015 Variables 22

Variable Type: User-Defined Variables


Viewing Variable Details:
In PowerShell, User Defined Variables,
Environment Variables, Functions, Registry
Keys, Aliases, and Certificates are stored on
virtual hard drives. The Get-PSDrive cmdlet
will provide a mapping of those variables
contained in virtual hard drives
There are 2 methods to view variables and
their values:

1. Change to the variable drive and use


Get-ChildItem cmdlet

2. Use the Get-Variable cmdlet


9/1/2015 Variables 23

Variable Type: User-Defined Variables


Viewing Variables:
Method 1:
$campusName = “York”
$count = 123
cd variable: (note colon after variable or function or env, etc.)
Get-ChildItem

Method 2:
$courseCode = “WIN213”
Get-Variable

Can get listing for each type of variable type issuing:

Get-ChildItem variable:
Get-ChildItem env:
Get-ChildItem alias:
etc
9/1/2015 Variables 24

Variable Type: User-Defined Variables


Confirming Variable Exists:
Instead of manually viewing the name and
value of a variable in the virtual hard drive, you
can issue a cmdlet to test to confirm that the
variable exists.

Example:

$clientAge = 20
Test-Path variable:\clientAge

The returning Boolean value will be true if


variable exists and false if variable does not
exist.
9/1/2015 Variables 25

Variable Type: User-Defined Variables


Setting / Clearing / Removing Variables:
Set-Variable
Change the value, options, etc. of an existing variable.
Note: you can’t set a variable those option has been
previously set to “read-only”.

Clear-Variable
Delete the data stored in a variable, but does not delete
the variable.

Remove-Variable
Deletes a variable and its value from the current
session. Note: you can’t remove a variable those option
has been previously set to “read-only”.

When the session closes, all user defined variables


are deleted unless written to the profile file
9/1/2015 Variables 26

Variable Type: User-Defined Variables


ErrorActionPreference Variable:
You can set the $ErrorActionPreference variable to either
stop if your script encounters a non-terminating error (type of
error that doesn’t end the script from running), or silently
continue with the script’s execution.

This is useful to instruct the script how to behave when it


encounters errors while you are running or debugging your
PowerShell script

Examples:
$ErrorActionPreference = "Stop"
$ErrorActionPreference = "SilentlyContinue"
9/1/2015 Variables 27

Additional Get-Help Features


In previous slides and labs, you learned
how to use the Get-Help cmdlet. There are
some interesting features associated with
Get-Help cmdlet that were not covered:

Update-Help
This allows you to download from the
Internet newer versions of help that may
include revisions or corrections.

Get-Help – ShowWindow
This displays help in a graphical dialog box
instead of the console pane. To customize
what elements of help appear in the help
dialog box (eg. like parameters), you
simply click Settings.
9/1/2015 Overview 28

File Management Script


Instructor Demonstration

• Your instructor will now provide a


demonstration in class in creating a
PowerShell script that applies the topics
that we learned in today’s class and
apply it to a practical task to administer
your Windows 2012 R2 server.

• This demonstration is one of the


PowerShell scripts you will be
performing in lab3.
We’ve Learned
1. There are two general classifications of programming languages:
interpreted and compiled. PowerShell is an interpreted programming
language. All programming languages have common characteristics,
including using variables, and performing logic and looping operations.

2. PowerShell can contain Windows commands, but really those


commands are just aliases for PowerShell cmdlets. You can use the
Get-Alias cmdlet to help find the PowerShell cmdlet for that particular
Windows command.

3. Variables allow administrators to create scripts that take different


action based on different situations. This makes scripts more powerful
and adaptive.

4. There are 3 general types of variables: Automatic (cannot change


value), Environment (could change value, but better to use for
existing system information), and user-defined (variables we can
create and store data).
We’ve Learned
5. There are “best practices” for how to name user-defined variables. You
have learned to create, clear values, change settings and remove
variables.

6. User-defined variables can be Un-Typed and Strongly-Typed. The


PowerShell interpreter will determine which data-type of the data
stored in the variable, but knowing which type of variable to use upon
creation can help to ensure that your script runs as intended.

7. All variables are contained in a Virtual Hard Drive in PowerShell. You


have learned techniques not only to see where these variables are
stored, but also test to see if a variable exists, which can be used for
logic statements later in this course.

8. You have learned additional features when obtaining help for


PowerShell cmdlets.

9. Your instructor reinforced the above learning topics by applying them


to a shell script that automates a file management task.

S-ar putea să vă placă și