Académique Documents
Professionnel Documents
Culture Documents
Module Overview
Use variables, arrays, escape characters, and advanced
operators
Variables
Think about shortcuts in Windows Explorer
Windows PowerShell
Variable Naming
Variable names usually consist of letters, numbers, and
$var = 5
The following example w assigns the object bound by GetService to the variable $services.
$services = Get-Service
Managing Variables
Variables are created, used, and managed through
$var = Hello
$var = 100
$var = ''
$var = $null
Six cmdlets are also available for managing variables
New-Variable
Set-Variable
Clear-Variable
Remove-Variable
Get-Variable
Dir variable:
techniques
Quotation Marks
Single and double quotation marks can be used to delimit
strings of characters.
When using double quotation marks, the shell looks for the
When executed, the shell will replaces the variable name with
its contents.
$var2 = $var World
$var3 = $var World
->
->
Hello World
$var World
marks
Escape Character
PowerShells escape character ` is used to take away the
Arrays
Arrays are variables that contain more than one object
Hashtables
Hashtables are special kinds of arrays where each element
Splatting
Splatting is a way to enter parameter names and values
parameter names and the values are the values for those
parameters
$parms = @{"ComputerName"="Server-R2";
"Class"="Win32_BIOS";
"Namespace"="root\cimv2"
}
Arithmetic Operators
Arithmetic operators can perform mathematical
Variable Types
The shell l permit you to put any type of object into any
Common types:
as eq and gt
Logon information
Virtual machine
LON-DC1
LON-SVR1
Contoso\Administrator Contoso\Administrator
Password
Pa$$w0rd
Pa$$w0rd
Lab Scenario
Youve been using PowerShell interactively for long enough
hashtables.
constructs like for, while, do, etc. so that you can take
advantage of them in your automation scripts.
Lab Review
How do you retrieve the members (properties and
single-quoted string?
Lesson 2: Scope
Explain the scope hierarchy in Windows PowerShell
Read and modify local and out-of-scope variables
Scope
Scope is designed to provide boundaries around
Run a script
Scope Rules
Three rules for scopes
New-Alias
New-PSDrive
New-Variable
Set-Variable
Remove-Variable
Clear-Variable
Get-Variable
elements
Best Practices
Scope can indeed create some very complex and confusing
scenarios.
script fail?
decisions
variable loops
collection of objects
Scripting Constructs
PowerShell has a relatively small number of scripting
IfElseIfElse
Switch
Break
For
While / Do / Until
ForEach
Reference IfElseIfElse
IfElseIfElse is a decision-making construct
commonly used
Nested Constructs
You often need to nest constructs within each other
Discuss: Where in the code below are the inner and outer
If constructs?
If ($ping.pingstatus eq 0) {
$wmi = gwmi win32_operatingsystem computer $computer
if ($wmi.buildnumber ne 7600) {
write 'Incorrect build ignoring computer'
}
}
Typing Constructs
Scripting constructs neednt necessarily be parts of a true
script
Reference: Switch
Switch is also designed to make logical decisions. It
Reference: For
For is used to repeat one or more commands a given
number of times
$var = 1
while ($var -lt 10) {
write $var
$var++
}
$var = 1
do {
write $var
$var++
} while ($var -lt 10)
$var = 20
do {
write $var
$var-} until ($var -lt 10)
Reference: ForEach
ForEach performs the same basic task as the ForEach-
$services = Get-Service
ForEach ($service in $services) {
Write $service.name
}
completely unnecessary!
language.
entire script
Logon information
Virtual machine
LON-DC1
Logon user
name
Password
LON-SVR1
LON-SVR2
LON-CLI1
Contoso\Adminis Contoso\Administ
trator
rator
Contoso\Administ
rator
Contoso\Administ
rator
Pa$$w0rd
Pa$$w0rd
Pa$$w0rd
Pa$$w0rd
Lab Scenario
Some of your junior IT staff could benefit from PowerShell
scripts but they dont have the skills yet to write them
themselves
Lab Review
Name three different keywords that allow you to do
something in a loop
or misspelling
Connectivity to computers
What else?
Error Actions
Many cmdlets can continue to execute, even after certain
Poor Practice
Remember: Errors are a good thing
Without errors, you will never discover where and when your
script is inappropriately executing
parameters
help about_commonparameters
Demonstration: -ErrorAction
Learn how to use the ErrorAction parameter
Trapping Exceptions
You can instruct the shell to notify you of terminating
ErrorAction
A Trap construct
A TryCatch construct
Exception Scope
Recall: A PowerShell session and its scripts work within
multiple scopes
Trap Constructs
Trap constructs are usually defined in scripts before the
trap {
write-host "Exception trapped!" -fore yellow -back black
continue
}
get-wmiobject win32_process -comp NotOnline -ea stop
At the end of a Trap construct, you will specify one of two
available keywords:
Break will exit the scope that contains the trap, passing the
original exception to the parent scope for handling
Trap Notes
The last slides trap was a general trap, meaning it will execute
trap
[System.Management.Automation.CommandNotFoundException]
{"Command error trapped"}
The preceding example executes only for exceptions of the
System.Management.Automation.CommandNotFoundException
type
Try Constructs
A TryCatch construct is more granular than a trap
try {
gwmi win32_service -comp notonline -ea stop
} catch {
write-host "Error!"
} finally {
write-host "This executes either way"
}
Three components exist for this construct:
The Try block defines the commands that you think might
cause an error. These are the commands for which youve
specified an ErrorAction of Stop.
and so on
In the code sample that follows, -EV captures the error into
the variable myerr
try {
gwmi win32_service -comp notonline -ea stop -ev myerr
} catch {
$myerr | out-file c:\errors.txt -append
}
consider using?
In what situations?
Logon information
Virtual machine
LON-DC1
LON-SVR1
Contoso\Administrator
Contoso\Administratorr
Password
Pa$$w0rd
Pa$$w0rd
Lab Scenario
You are assigned to update a Windows PowerShell script
the event log is the only way that you will be notified if the
script is not completing its audit as necessary
Lab Review
How can you find out what members the error records
have?
you?
How would you find any cmdlets that work with the event
log?
execution
Debugging Goal
Recall: The goal of debugging is to resolve logic errors
Trace Messages
Trace messages help you follow the flow of script
Step Debugger
Reviewing hundreds of lines in a large script for trace
Set-PSDebug step
Set-PSDebug off
Breakpoints
Stepping through large scripts can also be time-consuming
best?
Step debugger
Breakpoints
Write-Debug
Combinations?
Console
Logon information
Virtual machine
LON-DC1
Contoso\Administrator
Password
Pa$$w0rd
Lab Scenario
Your manager has provided you with several Windows
Lab Review
What are the key variables in your script and when are
they used?
other?
Lesson 6: Modularization
Modularize one or more commands into a basic function
Write a parameterized function
objects
function
Why Modularize?
Modularization is designed to make useful, reusable, self-
contained components.
different scripts?
Validating data
What else?
Basic Functions
A basic function accepts no input, which means it is
Function Output
The Write-Output cmdlet
Is aliased to Write.
Write-Output $var
Write $var
$var
Parameterized Functions
A parameterized function adds the ability to pass
Pipeline Input
Functions can also accept pipeline input
Filtering Functions
A filtering function is specially designed to accept pipeline
PROCESS executes one time for each object that was piped in
from the pipeline. Within this block, the special $_ placeholder
contains the current pipeline object.
END executes once after all of the pipeline input objects have
been processed. You can use this block to perform any cleanup tasks, such as closing a database connection.
function Do-Something {
BEGIN {}
PROCESS {}
END {}
}
function
Advanced Functions
An advanced function is a filtering function that specifies
function Get-ComputerDetails {
[CmdletBinding()]
param (
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$computername
)
BEGIN {}
PROCESS {}
END {}
}
Lab E: Modularization
Exercise 1: Generating an Inventory Audit Report
Logon information
Virtual machine
LON-DC1
Logon user
name
Password
LON-SVR1
LON-SVR2
LON-CLI1
Contoso\Administ Contoso\Administ
rator
rator
Contoso\Administ
rator
Contoso\Administ
rator
Pa$$w0rd
Pa$$w0rd
Pa$$w0rd
Pa$$w0rd
Lab Scenario
You now have the knowledge and experience you need to
You will use those skills to create two scripts, one for
Lab Review
What parameter attributes are used to indicate that a
ForEach-Object cmdlet?
What kinds of breakpoints can you set? Are breakpoints valid only in a