Beruflich Dokumente
Kultur Dokumente
0 for
the IT Professional
Part 1
<Trainer Name>
<Trainer Title>
<Trainer Alias>@Microsoft.com
Microsoft Confidential
Microsoft Confidential
Introductions
About You:
Name
Company Affiliation
Title/Function/Area of Responsibility
Product experience
Expectations for this Course
Microsoft Confidential
Microsoft Confidential
Workshop
Schedule
Microsoft Confidential
Start:
9:00 am
Break:
10:30 am
Lunch:
12:30 pm
Break:
2:45 pm
End:
5:00 pm
Microsoft Confidential
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 9: Pipeline 2
Module 10: Providers
DAY 3
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
DAY 4
DAY
DAY 2
DAY
DAY 1
1
Agenda
Lab
Environmen
t
2012R2-DC
2012R2-MS
Domain Controller
10.0.1.200
Domain Member
Server
10.0.1.210
WIN8-WS
Windows 8.1
Domain Member
Workstation
10.0.1.220
Password PowerShell4
Password PowerShell4
Microsoft Confidential
This training package is proprietary and confidential, and is intended only for uses described in the training materials. Content and software is
provided to you under a Non-Disclosure Agreement and cannot be distributed. Copying or disclosing all or any portion of the content and/or
software included in such packages is strictly prohibited.
The contents of this package are for informational and training purposes only and are provided "as is" without warranty of any kind, whether
express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, and noninfringement.
Training package content, including URLs and other Internet website references, is subject to change without notice. Because Microsoft must
respond to changing market conditions, the content should not be interpreted to be a commitment on the part of Microsoft, and Microsoft
cannot guarantee the accuracy of any information presented after the date of publication. Unless otherwise noted, the companies,
organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association
with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this
document. Except as expressly provided in written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this
document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
For more information, see Use of Microsoft Copyrighted Content at
http://www.microsoft.com/about/legal/permissions/
Microsoft, Internet Explorer, Outlook, SkyDrive, Windows Vista, Zune, Xbox 360, DirectX, Windows Server and Windows
are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Other Microsoft products
mentioned herein may be either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All
other trademarks are property of their respective owners.
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
Module 1: Introduction
Module Overview
Microsoft Confidential
Module 1: Introduction
Section 1: Shell
What is a Shell?
PowerShell Introduction
Section 2: PowerShell Features
Command-Line Interface (CLI)
Scripting Language
Interactive Scripting Environment (ISE)
PowerShell Web Access (PSWA)
PowerShell Workflow Overview
Desired State Configuration (DSC) Overview
Microsoft Confidential
10
Module 1: Introduction
Section 1: Shell
Lesson 1: What is
PowerShell?
Microsoft Confidential
11
What is a Shell?
rm
o
F
Ge
t-M
ail
bo
x
DIR
S
Sccrriip
p
tt
UII
G
GU
Software enabling OS
and Application access
through interactive
commands
or batches of commands
(scripts)
st
i
-L
t
a
Microsoft Confidential
12
What is PowerShell?
Automation Engine
Command-line Shell
Scripting Language
Development Framework:
o Integrated Scripting Environment
o PowerShell Embedded in Host
Applications
Microsoft Confidential
14
PowerShell Evolution
Microsoft Confidential
15
Microsoft Confidential
Microsoft Confidential
16
1.0
1.0 as
Update
2.0
2.0 as 3.0
Updat
e
(WMF)
3.0 as 4.0
Updat
e
(WMF)
XP
2003
Vista
2008
2008R
2
Win7
Win8
2012
WMF: Windows Management Framework
Win8.
Grouping
of several management related tools such as PowerShell, BITS, and the
1
WinRM
service
Microsoft Confidential
17
2012R
4.0 as
Updat
e
(WMF)
System Requirements
4.0
Microsoft Confidential
18
Installed by default
19
Module 1: Introduction
Section 2: PowerShell
Features
Lesson 1: PowerShell
Hosts
Microsoft Confidential
20
Microsoft Confidential
21
Windows 8 / Server
2012 Start Screen Tile
Taskbar Tile
Microsoft Confidential
22
Module 1: Introduction
Section 2: PowerShell
Features
Lesson 2: Scripting
Language
Microsoft Confidential
23
Scripting Language
Interactive Commands batched together:
Automation
Disaster Recovery
High Availability
Deployment
Auditing
Health Check
Monitoring
Reporting
GUI over PowerShell
Microsoft Confidential
24
Module 1: Introduction
Section 2: PowerShell
Features
Lesson 3: Interactive
Scripting Environment
(ISE)
Microsoft Confidential
25
Scripts
open
within a
tab
ShowComman
d add-on
Consol
e pane
Microsoft Confidential
26
Module 1: Introduction
Section 2: PowerShell
Features
Lesson 4: Extended
Features
Microsoft Confidential
27
Microsoft Confidential
Microsoft Confidential
29
Microsoft Confidential
32
PowerShell Workflow
Microsoft Confidential
Microsoft Confidential
34
Microsoft Confidential
Microsoft Confidential
40
Module 1: Introduction
End of Module
Microsoft Confidential
47
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
48
Module 2: Commands 1
Module Overview
Microsoft Confidential
49
Module 2: Commands 1
Section 1: Command Introduction
External Commands
Cmdlet Syntax
Cmdlet Common Parameters
Command Termination and Line Continuation
Section 2: Core Cmdlets
Get-Command and Show-Command
Get-Help
Section 3: Cmdlet Alternate Names
Built-in Aliases
User-defined Aliases
Microsoft Confidential
50
Module 2: Commands 1
Section 1: Command
Introduction
Lesson 1: External
Commands
Microsoft Confidential
51
External Commands
Use traditional tools like sc.exe, netsh.exe, reg.exe in PowerShell.exe
Runs in a separate process
Difficult to discover with no standard naming convention or syntax
Microsoft Confidential
52
Module 2: Commands 1
Section 1: Command
Introduction
Lesson 2: Cmdlets
Microsoft Confidential
53
What is a Cmdlet?
Microsoft Confidential
54
Anatomy of a Cmdlet
Command
Parameter
s
Command
Name
Verb
Noun
Paramete
r Name
Microsoft Confidential
Paramete
r Value
Switch
Parameter
55
Cmdlet Examples
PS C:\> Get-Process
Handles
NPM(K)
PM(K)
WS(K) VM(M)
----- -----
CPU(s)
------
Id ProcessName
-------
------
-----
-- -----------
83
1084
4124
45
0.09
7784 armsvc
179
13
1892
8216
89
0.66
6540 BDAppHost
56
Cmdlet Syntax
Syntax Definition
<Command-Name> -<Required Parameter Name> <Required Parameter Value>
[-<Optional Parameter Name> <Optional Parameter Value>]
[-<Optional Switch Parameters>]
[-<Optional Parameter Name>] <Required Parameter Value>
<Multiple Parameter Value>[]
Syntax Sample
PS C:\>
Microsoft Confidential
57
Syntax Legend
Microsoft Confidential
58
Microsoft Confidential
59
Microsoft Confidential
60
Microsoft Confidential
61
Microsoft Confidential
62
Microsoft Confidential
63
Microsoft Confidential
64
65
Module 2: Commands 1
Section 1: Command
Introduction
Lesson 3: Cmdlet
Common Parameters
Microsoft Confidential
66
Common Parameters
Parameters automatically available with any Cmdlet
Implemented by PowerShell not Cmdlet developer
Override system defaults or preferences
Microsoft Confidential
67
-PipelineVariable
(pv)
-Verbose (vb)
-WarningAction
(wa)
* Pipeline
is discussed Stores
in module
3
-WarningVariable
warnings
in a specified variable
(wv)
Microsoft Confidential
68
Example:
Common
Parameter
s in Use Verbose
Common
Parameter
Microsoft Confidential
69
Example:
Common
Parameter
s in Use ErrorAction
Common Parameter
Microsoft Confidential
Error Action
70
Example:
Store
command
output in a
specified
variable
name
Hash
Path
-----------
----
----
Note:SHA256
$ prefix denotes
in PowerShell
6A78a variable
C:\iExploreProcesses.csv
Microsoft Confidential
71
Variabl
e
Name
Microsoft Confidential
72
Example:
-WhatIf
Parameter
in use
if:
if:
if:
if:
if:
if:
Performing
Performing
Performing
Performing
Performing
Performing
the
the
the
the
the
the
operation
operation
operation
operation
operation
operation
"Stop-Process"
"Stop-Process"
"Stop-Process"
"Stop-Process"
"Stop-Process"
"Stop-Process"
on
on
on
on
on
on
target
target
target
target
target
target
"AcroRd32 (8160)".
"AcroRd32 (12756)".
"armsvc (2468)".
"atieclxx (3220)".
"atiesrxx (780)".
"audiodg (9576)".
...
Microsoft Confidential
73
Module 2: Commands 1
Section 1: Command
Introduction
Lesson 4: Command
Termination and Line
Continuation
Microsoft Confidential
74
Termination Characters
Statement Termination
;
Semi-colon can be used to execute more than one statement on a
single line
Microsoft Confidential
Microsoft Confidential
75
Example:
Use
command
terminatio
n
character
Status
-----Running
Name
---BITS
Id
Handles
CPU
Name
:
:
:
:
DisplayName
----------Background Intelligent Transfer Ser...
4
1308
1213.59375
System
Microsoft Confidential
76
Line Continuation
Statement Termination
>>
Still in the same statement
Complete syntax and include an empty line to finish the statement
and execute
Ctrl-C to break out and abort statement and line continuation
Microsoft Confidential
Microsoft Confidential
77
Example:
Line
Continuati
on
PS
>>
>>
>>
>>
This is a multi-line
string that continues
on several lines
until the syntax is completed
PS C:\>
Microsoft Confidential
78
Module 2: Commands 1
Lesson 1: Get-Command
and Show-Command
Microsoft Confidential
79
Get-Command
Discover Commands (cmdlets, functions, scripts, aliases)
Can show command syntax
Can also discover external commands (.exe, .cpl, .msc)
Microsoft Confidential
80
PS C:\> Get-Command
Example:
GetCommandType
Comman ----------Cmdlet
d
Name
---Add-Content
Definition
---------Add-Content [-Path]
String[]...
Cmdlet
Add-History
Add-History [[InputObject] ...
Cmdlet
Add-Member
Add-Member [-MemberType]
<PS...
Function
Clear-Host
$space = New-Object
System.A...
Alias
dir -> Get-Chil...
...
Microsoft Confidential
81
Example:
Wildcard
in Name
PS C:\>
CommandType
----------Function
Cmdlet
Cmdlet
Cmdlet
Cmdlet
Application
Application
Application
Application
Application
Name
---UpdateDefaultPreferencesWi...
Get-WinUserLanguageList
New-WinUserLanguageList
Set-WinUserLanguageList
Test-UserGroupMembership
DsmUserTask.exe
quser.exe
UserAccountBroker.exe
UserAccountControlSettings...
userinit.exe
Microsoft Confidential
82
Example:
List
Cmdlets
By Verb
Name
---Get-GPPermissions
Get-ProvisionedAppxPackage
Get-AppBackgroundTask
Microsoft Confidential
ModuleName
---------GroupPolicy
Dism
AppBackgroundTask
83
Exampl
e:
List
Cmdlet
s By
Noun
Name
---Get-Service
New-Service
Restart-Service
Resume-Service
Microsoft Confidential
ModuleName
---------Microsoft.PowerShell.Management
Microsoft.PowerShell.Management
Microsoft.PowerShell.Management
Microsoft.PowerShell.Management
84
Exampl
e:
List
Cmdlets
Only
Name
---Add-ADCentralAccessPolicyMember
Add-ADComputerServiceAccount
Microsoft Confidential
ModuleName
---------ActiveDirectory
ActiveDirectory
85
Example:
Single
Comman
d
PS C:\>
CommandType
----------Alias
Name
---dir -> Get-ChildItem
Microsoft Confidential
ModuleName
----------
86
Example:
List
Cmdlet
syntax
with GetComman
d
PS C:\>
Microsoft Confidential
87
Show-Command
Show-Command cmdlet launches GUI
Command Browser
Populate Parameters and Insert or Execute
Fill in
Parameters
Execute
Command
Directly
PS C:\> Show-Command
Insert
Command
with
Parameters
Populated
Start
Typing
Command
Name
and/or click
on
command
in list
88
Module 2: Commands 1
Lesson 2: Get-Help
Microsoft Confidential
89
Get-Help
Cmdlet help
Concept Help
Command Examples
Detailed Syntax
Microsoft Confidential
90
Example:
Help for
Cmdlets
Default
Short
View
Microsoft Confidential
91
Example:
Help for
Cmdlets
Full View
PS
PS
PS
PS
C:\>
C:\>
C:\>
C:\>
Get-Help
Get-Help
Get-Help
Get-Help
Get-ChildItem
Get-ChildItem Full
Get-ChildItem Examples
Get-ChildItem Detailed
NAME
SYNOPSIS
SYNTAX
DESCRIPTION
RELATED LINKS
REMARKS
NAME
SYNOPSIS
SYNTAX
DESCRIPTION
PARAMETERS
INPUTS
OUTPUTS
NOTES
EXAMPLES
RELATED LINKS
Microsoft Confidential
92
Example:
Help for
Specified
Cmdlet
Parameter(
s)
false
1
true (ByValue, ByPropertyName)
True
93
Module 2: Commands 1
Lesson 1: Aliases
Microsoft Confidential
94
Example:
Listing all aliases
PS C:\> Get-Alias
CommandType
Name
ModuleName
-----------
----
----------
Alias
Alias
Alias
Alias
Alias
Alias
Alias
...
% -> ForEach-Object
? -> Where-Object
ac -> Add-Content
asnp -> Add-PSSnapin
cat -> Get-Content
cd -> Set-Location
chdir -> Set-Location
Microsoft Confidential
95
Built-in Aliases
PowerShell provides short names for frequently used cmdlets
Ease of PowerShell adoption for Windows cmd.exe and *Nix
administrators
Saves time when typing interactive commands
Microsoft Confidential
96
Example:
Using built-in
aliases
Microsoft Confidential
97
Module 2: Commands 1
Lesson 2: User-defined
Aliases
Microsoft Confidential
98
Example:
Creating a
custom
alias
LastWriteTime
------------5/09/2013
1:40
21/10/2013
1:31
10/12/2013 10:26
1/12/2013
1:32
Microsoft Confidential
Length
-----PM
PM
AM
PM
Name
---Intel
Program Files
Program Files (x86)
Scripts
99
Module 2: Commands 1
Lab
Microsoft Confidential
100
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
101
Module 3: Pipeline 1
Module Overview
Microsoft Confidential
102
Module 3: Pipeline 1
Section 1: Pipeline Introduction
What is a pipeline?
Section 2: Pipeline Input
Get cmdlets, Text file and External Command
Section 3: Pipeline Object Manipulation
Object Cmdlets
Microsoft Confidential
103
Module 3: Pipeline 1
Section 1: Pipeline
Introduction
Lesson 1: What is a
pipeline?
Microsoft Confidential
104
What is a Pipeline?
Series of commands connected by the pipeline character
105
Module 3: Pipeline 1
Microsoft Confidential
106
Takes an action on
the services
Microsoft Confidential
107
External Commands
Can be used as input to the pipeline
External
command
PS C:\> whoami.exe
Contoso\administrator
PS C:\> whoami.exe | Split-Path -Parent
contoso
PS C:\> whoami.exe | Split-Path -Leaf
administrator
Microsoft Confidential
108
Microsoft Confidential
109
Import Cmdlets
Import structured text data into Windows PowerShell
Data can be processed by subsequent commands
110
Module 3: Pipeline 1
Lesson 1: Object
Cmdlets
Microsoft Confidential
111
Object Cmdlets
Name
Sort-Object
Select-Object
Group-Object
MeasureObject
CompareObject
Description
Sorts objects by property values
Selects object properties
Groups objects that contain the same value for specified
properties
Calculates numeric properties of objects, and the
characters, words, and lines in string objects, such as
text files
Compares two sets of objects
Microsoft Confidential
112
Example:
Sort-Object
Select-Object
NPM(K)
-----55
44
PM(K)
----21020
285244
WS(K) VM(M)
----- ----30340
1237
230112 1165
Microsoft Confidential
CPU(s)
-----477.78
716.45
Id ProcessName
-- ----------304 svchost
4124 livecomm
113
Example:
Group-Object
Group
----{System.Diagnostics.EventLogEntry,Sys...
{System.Diagnostics.EventLogEntry,Sys...
Microsoft Confidential
114
Example:
Measure-Object
Get files in c:\scripts then Measure their number (count) and total size
(length) in bytes
PS C:\> Get-ChildItem C:\Scripts |
Measure-Object -Property Length -Sum
Count
Average
Sum
Maximum
Minimum
Property
: 2
:
: 217837
:
:
: Length
Microsoft Confidential
115
Example:
Compare-Object
=>
116
Module 3: Pipeline 1
Lesson 1: Format
Cmdlets
Microsoft Confidential
117
Format Cmdlets
Convert pipeline objects into formatted output, typically for human
consumption
Should be last Cmdlet on the pipeline (only followed by Out-*
Cmdlets)
Microsoft Confidential
118
Example:
Format-List
with Default
Properties
PS C:\>
Id
Handles
CPU
Name
6400
472
0.78125
powershell
Microsoft Confidential
119
Example:
Format-List
with specific
properties
Name
: powershell
BasePriority : 8
PriorityClass : Normal
Microsoft Confidential
120
Example:
Format-Table
with default
properties
NPM(K)
PM(K)
WS(K) VM(M)
----- -----
CPU(s)
-------
------
-----
82
1308
1420
45
0.14
2308 armsvc
195
13
2568
3440
94
3.78
1192 atieclxx
110
852
1172
23
0.09
868 atiesrxx
565
20
6384
7092
113
42.14
4308 BasisSync
180
12
2276
2660
89
0.41
7744 BDAppHost
142
11
1860
1768
76
0.14
7712 BDExtHost
335
24
12120
14988
126
1.31
7772 BDRuntimeHost
413
. . .
31
8128
10668
209
1.39
6636 BingDesktop
Microsoft Confidential
------
Id ProcessName
-- -----------
121
Example:
Format-Table
with specific
properties
PS C:\> Get-Process |
Format-Table Property name,workingset,handles
Name
---csrss
csrss
csrss
dwm
dwm
explorer
Idle
LogonUI
lsass
MsMpEng
powershell_ise
...
WorkingSet
---------847872
356352
15646720
7045120
30498816
37539840
4096
6897664
7622656
24444928
144850944
Microsoft Confidential
Handles
------216
91
183
176
201
1427
0
367
1050
528
515
122
Example:
Format-Table with
specific
properties and
-AutoSize
PS C:\> Get-Process |
Format-Table -Property name,workingset,handles -AutoSize
Name
WorkingSet Handles
------------- ------csrss
843776
216
csrss
356352
91
csrss
15523840
183
dwm
7045120
176
dwm
30691328
201
explorer
37486592
1421
Idle
4096
0
LogonUI
6897664
367
lsass
7454720
1055
MsMpEng
22908928
527
powershell_ise 147017728
565
...
Microsoft Confidential
123
Example:
Format-Table
with specific
properties
Path
----
C:\Program
C:\Program
C:\Program
C:\Program
C:\Program
Fil...
Fil...
Fil...
Fil...
Fil...
WorkingSet
---------1454080
3760128
1200128
11911168
2736128
1826816
15331328
10981376
5857280
124
Example:
Format-Table
with Auto Sized
Columns
Path
----
C:\Program
C:\Program
C:\Program
C:\Program
C:\Program
Files
Files
Files
Files
Files
(x86)\Microsoft\BingDesktop\BDAppHost.exe
(x86)\Microsoft\BingDesktop\BDExtHost.exe
(x86)\Microsoft\BingDesktop\BDRuntimeHost...
(x86)\Microsoft\BingDesktop\BingDesktop.exe
(x86)\ATI Technologies\ATI.ACE\Core-Stati...
125
PS C:\> Get-Process |
Format-Table -Property Name,Path,WorkingSet -AutoSize Wrap
Example:
Format-Table
with Wrap
Name
---armsvc
atieclxx
atiesrxx
BDAppHost
Path
----
Microsoft Confidential
126
Example:
Format-Table
with Grouping
PS C:\> Get-Process |
Sort-Object -Property BasePriority |
Format-Table -GroupBy BasePriority -Wrap -AutoSize
Count Name
----- ---181027 SuccessAudit
25 FailureAudit
Autosize minimizes
data truncation, wrap
eliminates it
Group
----{System.Diagnostics.EventLogEntry}
{System.Diagnostics.EventLogEntry}
Microsoft Confidential
127
Example:
Format-Wide
Default 2
Columns
[Program Files]
[PShell]
[Windows]
Output displayed in 2
columns by default
Microsoft Confidential
128
Example:
Format-Wide
Explicit number
of Columns
[PerfLogs]
[Users]
[Program Files]
[Windows]
Output displayed in 3
columns
Microsoft Confidential
129
Example:
Format-Wide
AutoSize
maximizes
columns
?
clear
compare
dbp
epal
fl
gci
gl
ac
clhy
copy
del
epcsv
foreach
gcm
gm
asnp
cli
cp
diff
epsn
ft
gcs
gmo
cat
clp
cpi
dir
erase
fw
gdr
gp
cd
cls
cpp
dnsn
etsn
gal
ghy
gps
Output displayed in
max numbers of
columns based on
widest data
Microsoft Confidential
130
chdir
clv
curl
ebp
exsn
gbp
gi
group
Module 3: Pipeline 1
Microsoft Confidential
131
Export Cmdlets
Export pipeline objects to text file
Should be last cmdlet on the pipeline
Microsoft Confidential
132
Example:
ExportClixml
Microsoft Confidential
133
Example:
ExportCSV
-NoTypeInformation
parameter avoids
this as 1st line
Microsoft Confidential
134
Example:
ImportCsv
Microsoft Confidential
135
Module 3: Pipeline 1
Microsoft Confidential
136
Out Cmdlets
Sends command output to a specified device
Name
Description
Out-Default
Out-File
OutGridView
Out-Host
Default
Sends output to PowerShell host
Paging switch parameter displays one page at a time
Out-Null
Out-Printer
Out-String
137
Example:
OutGridview
Microsoft Confidential
138
Microsoft Confidential
139
Module 3: Pipeline 1
Microsoft Confidential
141
Group
----- ----
----Microsoft Confidential
142
Module 3: Pipeline 1
Lab
Microsoft Confidential
143
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
144
Module 4: Commands 2
Module Overview
Microsoft Confidential
145
Module 4: Commands 2
Section 1: Script Blocks
What is a Script Block?
Section 2: Functions
Functions Introduction
Section 3: Remoting
Introduction to PowerShell Remoting
Using PowerShell Remoting
Microsoft Confidential
146
Module 4: Commands 2
Lesson 1: What is a
Script Block?
Microsoft Confidential
147
148
Example:
Cmdlet
with
ScriptBloc
k
parameter
argument
PM(K)
----48316
1948
7768
WS(K) VM(M)
CPU(s)
----- ---------64252
237 3,077.20
7180
60
3.55
18512
286
0.16
Id
-1840
9356
14092
:
:
:
:
:
0
0
2
933
29332816
Microsoft Confidential
149
ProcessName
----------CcmExec
conhost
csrss
Module 4: Commands 2
Section 2: Functions
Lesson 1: Functions
Introduction
Microsoft Confidential
150
What is a Function?
Functions
Microsoft Confidential
151
Function keyword
Name
Optional named parameters
One or more commands/pipelines
Basic Syntax:
function <name>
{
param ($parameter1,$parameterN)
<statement list>
}
Microsoft Confidential
Microsoft Confidential
152
Example:
Creating a
utility
function
PS C:\> Get-ServiceInfo
Microsoft Confidential
153
Example:
Creating a
utility
function with
parameters
Microsoft Confidential
154
Module 4: Commands 2
Section 3: Remoting
Lesson 1: Introduction
to PowerShell Remoting
Microsoft Confidential
155
Entry Point
Various
PowerShell
Remote
Administratio
n Techniques
Transport
ResourceSpecific
Cmdlets
Native OS
Remoting
WMI Cmdlets
Networ
k
DCOM
RPC
CIM Cmdlets
TCP/IP
Microsoft Confidential
Entry Point
Various
PowerShell
Remote
Administratio
n Techniques
Transport
ResourceSpecific
Cmdlets
Native OS
Remoting
WMI Cmdlets
Networ
k
DCOM
RPC
CIM Cmdlets
CDXML Cmdlets
CIM Sessions
Connection
Settings Only,
Non-Stateful
DSC Cmdlets
Microsoft Confidential
TCP/IP
WS-MAN
Entry Point
Various
PowerShell
Remote
Administratio
n Techniques
WMI Cmdlets
DCOM
RPC
CIM Cmdlets
CDXML Cmdlets
Featured in
this Module
Transport
ResourceSpecific
Cmdlets
Native OS
Remoting
Networ
k
CIM Sessions
Connection
Settings Only,
Non-Stateful
DSC Cmdlets
Workflows
Remoting
Cmdlets
PSSessions
Stateful
Connection
Microsoft Confidential
TCP/IP
WS-MAN
Microsoft Confidential
159
PS C:\>
Interactive (1:1)
PS C:\>
PS C:\>
160
Requirements
Local and Remote Computers:
PowerShell 2.0 or later (feature enhancements with newer
versions)
161
Enabling Remoting
Use local command or Group Policy
Microsoft Confidential
162
Module 4: Commands 2
Section 3: Remoting
Lesson 2: Using
PowerShell Remoting
Microsoft Confidential
163
Example:
Interacti
ve
Session
[2012R2-DC] PS C:\>
[2012R2-DC] PS C:\> Hostname
2012R2-DC
Ending a
session
Local
Computer
165
Example:
Invoke a
command
Name
---en-AU
DisplayName
----------English (Australia)
PSComputerName
-------------2012R2-DC
166
Example:
Invoke a
command
(1:many)
Name
---en-US
en-US
DisplayName
----------English (United States)
English (United States)
PSComputerName
-------------2012R2-MS
2012R2-DC
167
Example:
Use
alternate
credential
Name
---en-AU
DisplayName
----------English (Australia)
PSComputerName
-------------2012R2-DC
168
Example
:
Persiste
nt
Session
(repeat
use)
Name
---en-AU
DisplayName
----------English (Australia)
PSComputerName
-------------2012R2-DC
169
Example
:
Persiste
nt
Session
(repeat
use)
1:many
Name
---Session1
Session2
ComputerName
-----------2012R2-DC
2012R2-MS
State
----Opened
Opened
ConfigurationName
----------------Microsoft.PowerShell
Microsoft.PowerShell
Availability
-----------Available
Available
Name
DisplayName
PSComputerName
----
----
-----------
--------------
1033
en-US
2012R2-DC
170
Module 4: Commands 2
Lab
Microsoft Confidential
171
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
172
Module 5: Scripts
Module Overview
Microsoft Confidential
173
Module 5: Scripts
Section 1: Introduction to Scripts
What is a Script?
Section 2: Running Scripts
Execution Policies
Launching a script
Section 3: Script Parameters
The Param Statement
Microsoft Confidential
174
Module 5: Scripts
Section 1: Introduction to
Scripts
Lesson 1: What is a
Script?
Microsoft Confidential
175
What is a Script?
Reusable code
Text file (.ps1) containing one or more PowerShell commands
Simple code packaging for distribution purposes
Can also:
Microsoft Confidential
176
Example:
Simple
script
Microsoft Confidential
177
Module 5: Scripts
Lesson 1: Execution
Policies
Microsoft Confidential
178
Execution
Policy
Levels
Microsoft Confidential
179
Execution
Policy
Scope
Apply
Execution
Policy
Levels at
one or more
of these 5
scopes
Highest
Priority
Wins
Microsoft Confidential
180
Script Execution
Default Execution Policy (restricted) prevents any scripts
from running
Must be changed to run any scripts
Execution Policy is saved in the registry, and therefore only
needs to be changed once per computer
Microsoft Confidential
181
Example:
Determine
Execution
Policy in
effect
PS C:\> Get-ExecutionPolicy
RemoteSigned
182
Example:
Determin
e Why
Execution
Policy in
effect
ExecutionPolicy
--------------Undefined
Undefined
Undefined
Undefined
RemoteSigned
Top most
takes
precedence
Effective
Policy
183
Example:
Set
Execution
Policy User
184
Example:
Set
Execution
Policy Computer
185
Exampl
e:
Script
Signing
Codesigning certificate
Trusted by computer where script
will run
Step 1: Create a certificate variable
PS C:\> $cert = Get-ChildItem Cert:\CurrentUser\my\A4...
>> -CodeSigningCert
Step 2: Sign script
PS C:\> Set-AuthenticodeSignature .\ISECPUTime.ps1 $cert
Directory: C:\Scripts
SignerCertificate
----------------A4..
Status
-----Valid
Microsoft Confidential
Path
---ISECPUTime.ps1
186
Exampl
e:
Script
Before
Signing
Microsoft Confidential
187
Exampl
e:
Script
After
Signing
Script signature
block
Microsoft Confidential
188
Module 5: Scripts
Lesson 2: Launching a
script
Microsoft Confidential
189
Running a
Script
Microsoft Confidential
190
Microsoft Confidential
191
Microsoft Confidential
192
Module 5: Scripts
Section 3: Script
Parameters
Microsoft Confidential
193
Param Statement
Must be first statement in script, except for comments
Parameter values are available to commands in script
Param
Statement
Paramet
er
Parameter
Value
194
Module 5: Scripts
Lesson 1: Single-line
and Block Comments
Microsoft Confidential
195
Single-Line Comments
#
Comment
character
Microsoft Confidential
196
Block Comments
<#
#>
Block comment
tags
Microsoft Confidential
197
Module 5: Scripts
Lesson 2: #Requires
Statement
Microsoft Confidential
198
Requires Statement
Special comment
Prevents script from running without required elements
Can only be used in scripts (not functions, cmdlets, etc)
Requires Option
Supported in PS
Version
2.0+
2.0+
2.0+
3.0+
#Requires -RunAsAdministrator
4.0+
Microsoft Confidential
199
Version Requirement
Prevents script from running on lower PowerShell versions
o Script errors at start
o Avoids unexpected errors from unsupported language, cmdlets,
etc.
Microsoft Confidential
200
Administrator Requirement
Script requires elevated user rights
o Script errors at start indicating
o Avoids unexpected errors in script
#requires -RunAsAdministrator
Get-ChildItem c:\ -Hidden
Microsoft Confidential
201
Module 5: Scripts
Section 5: Command
Precedence
Lesson 1: Explore
command precedence
rules
Microsoft Confidential
202
Note: If the same type of command with the same name exists,
PowerShell runs the command that was added to the session most
recently
Microsoft Confidential
203
Example:
Replace
another
command
Source
Destination
IPV4Address
IPV6Address
------
-----------
-----------
-----------
WIN8-WS
2012r2-ms
10.0.1.210
WIN8-WS
2012r2-msMicrosoft Confidential10.0.1.210
204
Example:
Module
Qualify
Command
Name
Handles
------1427
NPM(K)
-----0
PM(K)
----140
WS(K) VM(M)
----- ----4232
16
CPU(s)
------
Id ProcessName
-- ----------4 System
NPM(K)
-----0
PM(K)
----140
WS(K) VM(M)
----- ----4232
16
Microsoft Confidential
CPU(s)
------
Id ProcessName
-- ----------4 System
205
Module 5: Scripts
Section 6: Integrated
Scripting Environment (ISE)
Lesson 1: ISE
Microsoft Confidential
206
Name
------PowerShellRoot
PowerShell
PowerShell-V2
PowerShell-ISE
Install State
------------Installed
Installed
Available
Available
Restart
-------No
Feature Result
---------------{Windows PowerShell ISE}
207
Launch ISE
Filename: powershell_ise.exe
Alias in PowerShell.exe: ISE
Microsoft Confidential
208
Microsoft Confidential
209
Crash Recovery
Uses alternate auto-saved files to restore un-saved
scripts
Microsoft Confidential
210
Microsoft Confidential
211
ISE IntelliSense
Similar to Visual Studio IntelliSense
Dynamically suggests code and
provides help as you type
Keyboard-based tab completion
still works
Mouse or keyboard can be used to
leverage IntelliSense popups
Works in Script and Command Pane
Examples on following slides
Microsoft Confidential
212
Example:
IntelliSens
e
Parameter
s
Microsoft Confidential
213
Example:
IntelliSense
Parameter
Arguments
Microsoft Confidential
214
215
Collapsable Code
Code can be collapsed for easier reading
Functions, Script block, Parenthesis,
Quotes, etc. can be collapsed spanning
multiple lines
Manual code regions allow collapsing
between any two lines
o #region Begin a Region
o #endregion End a Region
o Region tags must be lowercase
o Optional text following the #region tag can help
with code documentation
Microsoft Confidential
216
Brace Matching
ISE script pane will highlight matching braces when cursor positioned
outside
Works with: { Curly Braces }, ( Parentheses ), [ Square Brackets ]
Find paired braces with ISE menu: Edit Go to Match ( CTRL+] )
Microsoft Confidential
217
Microsoft Confidential
218
Example:
ISE Snippet
Insertion
Ctrl-J
or
Edit -> Start
Snippets
Microsoft Confidential
219
Microsoft Confidential
220
Module 5: Scripts
Lab
Microsoft Confidential
221
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
222
Module Overview
Microsoft Confidential
223
Microsoft Confidential
224
Microsoft Confidential
225
Example:
Concept
help in the
console
----
about_Aliases
to...
about_Arithmetic_Operators
op...
about_Arrays
arrays...
about_Assignment_Operators
tp...
about_Automatic_Variables
HelpFile
Describes how
HelpFile
Describes the
HelpFile
Describes
HelpFile
Describes how
HelpFile
Describes
Microsoft Confidential
226
Example:
Concept
help in the
ISE
2
3
Microsoft Confidential
227
Lesson 1: Updatable
Help
Microsoft Confidential
228
Updatable Help
Help contents not shipped with v3.0+
Help topics must be downloaded before they can be used locally
o Update-Help (pulls from direct Internet access or offline copies)
o Save-Help (allows help to be re-distributed)
229
Help
e
t
a
Upd
Internet
Update-Help
Upd
ate-
Help
Microsoft Confidential
230
Only updates Help once per day even if run multiple times
o -Force can be used to update each time
231
Save-Help
DestinationPath
Internet
Optional Default
source path
location GPO
Setting
Microsoft Confidential
Up
-So date
ur -He
ce
Pa lp
th
te
a
d
Up
e
-H
So
p
llpp
H
Hee
ttee-- PPaatthh
ddaa
U
Upp uurrccee
--SSoo
Internal
machines do not
need Internet
access
th
a
P
rce
o On
without Internet Access (with GPO source path):
PScomputers
C:\> Update-Help
GPO Setting:
Computer > Policies> Administrative Templates > Windows Components
> Windows PowerShell
Enable "Set the default source path for Update-Help."
Microsoft Confidential
233
Microsoft Confidential
234
Microsoft Confidential
235
Get-Help -ShowWindow
Display Help in floating
window
236
Microsoft Confidential
237
238
Keywords
.SYNOPSIS
.DESCRIPTION
.PARAMETER <parameter name>
.EXAMPLE
.INPUTS
.OUTPUTS
.NOTES
.LINK
.COMPONENT
Microsoft Confidential
239
Example
:
Function
Help
PS C:\> Get-Help Get-SysLogNN -Full
NAME
Get-SysLogNN
SYNOPSIS
Function that returns the most recent system event log entries.
SYNTAX
Get-SysLogNN [[-Log] <Object>] [[-NumberOfEvents] <Object>]
[<CommonParameters>]
...
Microsoft Confidential
240
Example
:
Script
Help
241
Lab
Microsoft Confidential
242
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
243
Module 7: Object
Models
Module Overview
Microsoft Confidential
244
Microsoft Confidential
245
Section 1: Objects in
PowerShell
Lesson 1: What is an
object?
Microsoft Confidential
246
What is an Object?
Structured Data
Combines similar information and capabilities into
one entity
A collection of parts and how to use them
Microsoft Confidential
Microsoft Confidential
247
The Bike
Object
Parts
Properties
How to use
Methods
Front Wheel
Pedal
Back Wheel
Brake
Pedals
Steer Left
Colour
Steer Right
Wheelie
Size
Microsoft Confidential
Microsoft Confidential
248
Objects
and Types
Bike
Size Property
Colour Property
Brake() Method
Wheelie() Method
$Bike1.Size = "Large"
$Bike1.Colour = "Green"
$Bike3.Size = "Medium"
$Bike3.Colour = "Yellow"
$Bike3.Wheelie()
$Bike2.Size = "Small"
$Bike2.Colour = "Blue"
Microsoft Confidential
249
Object-Based Shell
Everything is represented as an OBJECT
OBJECTS have data fields (PROPERTIES) and procedures (METHODS)
PROPERTIES and METHODS are collectively known as MEMBERS
An OBJECT is an INSTANCE of a TYPE
A TYPE represents a construct that defines a template of MEMBERS
Microsoft Confidential
250
Section 1: Objects in
PowerShell
Lesson 2: Identify
PROPERTIES and
METHODS for an object
Microsoft Confidential
251
Get-Member
Get-Member displays PROPERTIES and METHODS
PROPERTIES are columns of information
METHODS are actions that can be taken
Typically used in pipeline
Microsoft Confidential
252
Example:
Find
object
member
s
MemberType
---------Method
Method
Method
Method
Method
Definition
---------System.IO.StreamWriter AppendText()
System.IO.FileStream Create()
System.IO.StreamWriter CreateText()
void Decrypt()
void Delete()
Property
Property
Property
Property
System.IO.FileAttributes Attributes
datetime CreationTime {get;set;}
datetime CreationTimeUtc {get;set;}
System.IO.DirectoryInfo Directory {get;}
Microsoft Confidential
253
Example:
Find
object
member
s
MemberType
---------Method
Method
Method
Method
Method
Definition
---------System.IO.StreamWriter AppendText()
System.IO.FileStream Create()
System.IO.StreamWriter CreateText()
void Decrypt()
void Delete()
Property
Property
Property
Property
System.IO.FileAttributes Attributes
datetime CreationTime {get;set;}
datetime CreationTimeUtc {get;set;}
System.IO.DirectoryInfo Directory {get;}
Microsoft Confidential
254
Example:
Retrieving
Property
using dot
notation
(Variable)
Microsoft Confidential
256
Example:
Retrieving
Property
using dot
notation
(Variable)
$csvhash | Get-Member
TypeName: Microsoft.Powershell.Utility.FileHash
Name
---Equals
GetHashCode
GetType
ToString
Algorithm
Hash
MemberType
---------Method
Method
Method
Method
NoteProperty
NoteProperty
Definition
---------bool Equals(System.Object obj)
int GetHashCode()
type GetType()
string ToString()
System.String Algorithm=SHA256
System.String Hash=207...
$csvhash.Hash
207267C4B159E53C2272E6574DD89C78CF83648133698D793AB727D8CDF9
Microsoft Confidential
257
Example:
Retrieving
Property
using dot
notation
(Command)
MemberType
---------Method
Definition
---------bool Equals(System.Object obj)
GetHashCode Method
int GetHashCode()
GetType
Method
type GetType()
ToString
Method
string ToString()
Hash
NoteProperty System.String Hash=207...
207267C4B159E53C2272E6574DD89C78CF83648133698D793AB727D8CDF9
Microsoft Confidential
258
Exampl
e:
Call
method
on an
object
Definition
---------void BeginErrorReadLine()
void BeginOutputReadLine()
void CancelErrorRead()
void CancelOutputRead()
void Close()
bool CloseMainWindow()
System.Runtime...
void Dispose(),
void Kill()
259
Section 1: Objects in
PowerShell
Microsoft Confidential
260
Example 1:
Find the object
TYPE returned by
the
Get-Date cmdlet
MemberType
---------Method
Method
Method
Definition
---------datetime Add(timespan value)
datetime AddDays(double value)
datetime AddHours(double value)
Microsoft Confidential
261
Example 2:
Find the object
TYPE returned by
the
Get-Date cmdlet
PS C:\> (Get-Date).GetType()
IsPublic IsSerial Name
-------- -------- ---True
True
DateTime
Microsoft Confidential
262
Lesson 1: Where do
TYPES come from?
Microsoft Confidential
263
Collections of TYPES
Simplify coding by providing pre-defined TYPES
Provide a consistent interface
Examples:
.NET Framework
Component Object Model (COM)
Windows Management Instrumentation (WMI)
Microsoft Confidential
264
Lesson 2: ISE
IntelliSense and Member
Completion
Microsoft Confidential
266
Propert
y
Method
Microsoft Confidential
267
Module 7: Object
Models
Lab
Microsoft Confidential
268
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
269
Module 8: Operators 1
Module Overview
Microsoft Confidential
270
Module 8: Operators 1
Section 1: Comparison
Comparison Operators
Section 2: Logical
Logical Operators
Microsoft Confidential
271
Module 8: Operators 1
Section 1: Comparison
Operators
Lesson 1: Comparison
Operators
Microsoft Confidential
272
Comparison Operators
Compare values
Useful when testing conditions (If, Switch, Where-Object, etc.)
Do not use = , > , < , ==, etc. to compare values
Object type on left governs comparison
Microsoft Confidential
273
ceq
cne
cgt
Greater Than or
ge Equal To
cge
CaseSensitive
-lt Less Than
-clt
Version
-le Less Than or Equal To -cle
Microsoft Confidential
274
Example 1:
Basic
operators
PS C:\> 1 -eq 1
True
PS C:\> 1 -eq 2
False
PS C:\> 10 -gt 20
False
PS C:\> 10 -gt 5
True
Microsoft Confidential
275
Example 2:
Basic
operators
Microsoft Confidential
276
-clike
cnotlik
Casee
Sensitive
Sensitive
Version
Allowed Wildcards
*
Microsoft Confidential
277
Example:
-Like
------- ------
724
8972
628
13 51.33
4 System
Must be 7 chars
followed by zero or
278
more
-match
Regular Expression
comparison
Regular Expression NOT
notmatc comparison
h
Microsoft Confidential
-cmatch
Casecnotmat
Sensitive
ch Version
279
Example:
-Match
Microsoft Confidential
280
Sensitive
Version
-ccontains
cnotcontai
ns
-in
-notin
Single in Array
Single not in Array
-cin
-cnotin
Microsoft Confidential
CaseSensitive
281
Version
Example:
Array
Containment
Microsoft Confidential
282
Example:
Array
Containment
Microsoft Confidential
283
Example:
Operator
Case
Sensitivity
284
Module 8: Operators 1
Section 2: Logical
Operators
Lesson 1: Logical
Operators
Microsoft Confidential
285
Logical Operators
Connect statements
Compound conditions
Operator Description
-and
-or
-xor
TRUE only when one of the statements is TRUE and the other
is FALSE.
Negates the statement that follows it.
-not or !
Microsoft Confidential
286
Examples:
-and
-or
-xor
-not
(5 lt 4)
Microsoft Confidential
287
Module 8: Operators 1
Lesson 1: Range
Operators
Microsoft Confidential
288
Range Operator
Numerical
PS C:\> 1..10
1
2
3
4
5
6
7
8
9
10
PS C:\> 11..20
11
12
13
14
15
16
17
18
19
20
Microsoft Confidential
PS C:\> 5..-5
5
4
3
2
1
0
-1
-2
-3
-4
-5
289
Length Name
------ ----
d----
20/05/2014
8:22 AM
AppLocker
d----
19/10/2013
8:19 AM
appmgmt
Microsoft Confidential
290
LastWriteTime
------------23/08/2013
23/08/2013
23/08/2013
22/08/2013
22/08/2013
22/08/2013
1:36
1:36
5:12
9:03
9:11
9:01
AM
AM
AM
PM
PM
PM
Microsoft Confidential
Length Name
------ ----
25600
142848
53760
429568
ja-JP
zh-CN
jnwmon.dll
joy.cpl
jsproxy.dll
zipfldr.dll
291
Module 8: Operators 1
Section 4: Numeric
Multipliers
Lesson 1: Numeric
Multipliers
Microsoft Confidential
292
Example
PS C:\> 2kb
2048
megabyte (n * 1024 x 1024)
PS C:\> 100mb
104857600
gigabyte (n * 1024 x 1024 x 1024) PS C:\> 1.5gb
1610612736
terabyte (n * 1024 x 1024 x 1024 x PS C:\> 1tb
1024)
1099511627776
petabyte (n * 1024 x 1024 x 1024 x PS C:\> 1pb
1024 x 1024)
1125899906842624
Microsoft Confidential
293
Module 8: Operators 1
Lab
Microsoft Confidential
294
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
295
Module 9: Pipeline 2
Module Overview
Microsoft Confidential
296
Module 9: Pipeline 2
Section 1: Pipeline Objects
Pipeline Variable
Section 2: Pipeline Cmdlets
Other Object Cmdlets
Section 3: Pipeline Processing
Begin, Process and End Blocks
Section 4: Cmdlet Parameter Pipeline Input
Two ways to accept pipeline input
Microsoft Confidential
297
Module 9: Pipeline 2
Lesson 1: Pipeline
Variable
Microsoft Confidential
298
Pipeline Variable
When multiple objects are piped, PowerShell sends objects one at a time
Built-in variables $_ and $PSItem represent current object on pipeline
Used to perform an action on every object
Use -PipelineVariable parameter to name your own variable on the pipeline
Scoped only to current pipeline
Both lines produce the same result
PS C:\> Get-Process | Where-Object {$psitem.ws -gt 100MB}
PS C:\> Get-Process | Where-Object {$_.ws -gt 100MB}
Storing cmdlet output in a user-defined variable
PS C:\> Get-Process -PipelineVariable CurrentProcess |
Where-Object {$CurrentProcess.ws -gt 100MB}
Microsoft Confidential
299
Module 9: Pipeline 2
Microsoft Confidential
300
Microsoft Confidential
301
Example:
ForEachObject
Netlogon
Netman
netprofm
NetTcpPortSharing
Microsoft Confidential
302
Example:
Pipeline
Filtering
with WhereObject
(FileInfo)
(*.txt)
(FileInfo)
(*.txt)
(Length > 10240)
(FileInfo)
(*.txt)
(Length > 10240)
(Sorted by length)
(FileInfo)
(*.txt)
(Length > 10240)
(Sorted by length)
(Formatted in table)
303
Example:
WhereObject
(Simple
syntax)
PowerShell v1.0+
Microsoft Confidential
No compound
conditions with
simplified syntax
304
Example:
Filtering with
Parameters vs.
Where-Object
Microsoft Confidential
305
Example:
Automatic
Member
Enumeration
Single level
PS C:\> (Get-Process).ID
4300
8844
8812
Doesnt work in
PowerShell v1.0 and
v2.0
Name
---Tuesday
Monday
Group
----{Tuesday, Tuesday, Tuesday...}
{Monday, Monday, Monday...}
Microsoft Confidential
306
Module 9: Pipeline 2
Section 3: Pipeline
Processing
Microsoft Confidential
307
308
Microsoft Confidential
309
Microsoft Confidential
310
Microsoft Confidential
311
Process Block
End block
312
Exampl
e:
Named
Blocks
function My-Function
{
Begin
{
Remove-Item .\Events.txt
Write-Host "Start" -ForegroundColor Red
}
Process
{
$_.Message | Out-File -Filepath Events.txt -Append
}
End
{
Write-Host "End" -ForegroundColor Green
notepad.exe Events.txt
}
}
313
Module 9: Pipeline 2
Section 4: Cmdlet
Parameter Pipeline Input
Microsoft Confidential
314
Microsoft Confidential
315
-ComputerName <String[]>
Specifies one or more remote computers. The default is ...
Required?
Position?
Default value
Accept pipeline input?
Accept wildcard characters?
false
1
Local computer
True (ByValue, ByPropertyName)
false
Microsoft Confidential
316
Microsoft Confidential
317
false
1
Local computer
True (ByValue, ByPropertyName)
false
319
Microsoft Confidential
320
false
1
Local computer
True (ByValue, ByPropertyName)
false
1.
2.
3.
4.
5.
6.
Bind
Bind
Bind
Bind
Bind
Bind
Microsoft Confidential
323
Module 9: Pipeline 2
Lab
Microsoft Confidential
324
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
325
Module Overview
Microsoft Confidential
326
Microsoft Confidential
327
Section 1: Providers
Introduction
Microsoft Confidential
328
Microsoft Confidential
329
Active Directory
SQL Server
Microsoft Confidential
330
Microsoft Confidential
331
Lesson 1: Built-in
Providers
Microsoft Confidential
332
Built-in Providers
Provider
Drive
Data Store
Alias
Alias:
Certificate
Cert:
Environment
Env:
FileSystem
Function
Function:
Registry
HKLM:, HKCU:
Windows registry
Variable
Variable:
WSMan
WSMan:
WS-Management configuration
information
Microsoft Confidential
333
Lesson 1: Provider
Cmdlets
Microsoft Confidential
334
Example:
GetPSProvider
Capabilities
-----------ShouldProcess
ShouldProcess
Filter, ShouldProcess, Credentials
ShouldProcess
ShouldProcess, Transactions
ShouldProcess
ShouldProcess
Credentials
Drives
-----{Alias}
{Env}
{C}
{Function}
{HKLM, HKCU}
{Variable}
{Cert}
{WSMan}
335
Microsoft Confidential
337
Example:
GetPSDrive
Root
---C:\
\
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
338
Example:
New-PSDrive
RemovePSDrive
339
Microsoft Confidential
340
Item Cmdlets
Name
Example
Get-Item
Get-ChildItem
Copy-Item
Move-Item
Clear-Item
Microsoft Confidential
341
Item Cmdlets
Name
Example
RemoveItem
Set-Item
RenameItem
Microsoft Confidential
342
Lesson 4: ItemProperty
Cmdlets
Microsoft Confidential
343
ItemProperty Cmdlets
Name
Example
GetItemProperty
CopyItemProperty
MoveItemProperty
ClearItemProperty
Microsoft Confidential
344
ItemProperty Cmdlets
Name
Example
RemoveItemProperty
Set-ItemProperty
New-ItemProperty
RenameItemProperty
Microsoft Confidential
345
Lesson 5: Content
Cmdlets
Microsoft Confidential
346
Content Cmdlets
Name
Example
ClearContent
Microsoft Confidential
347
Lesson 6: Location
Cmdlets
Microsoft Confidential
348
Location Cmdlets
Name
Example
GetLocation
PS C:\> Get-Location
C:\
SetLocation
Microsoft Confidential
349
Microsoft Confidential
350
Path Cmdlets
Name
Example
Test-Path
Join-Path
Split-Path
Microsoft Confidential
351
Path Cmdlets
Name
Example
ConvertPath
ResolvePath
Microsoft Confidential
352
Examples:
Alias:
PS C:\> $alias:dir
Get-ChildItem
Env:
PS C:\> $Env:windir
C:\windows
Function:
PS C:\> $function:more
param([string[]]$paths)
{}
Variable:
PS C:\> $variable:ref
localhost
server1
server2
Microsoft Confidential
353
Lab
Microsoft Confidential
354
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
355
Module Overview
Microsoft Confidential
356
Microsoft Confidential
357
Section 1: Variables
Microsoft Confidential
358
359
Section 2: Kinds of
Variables
Lesson 1: Automatic
Variables
Microsoft Confidential
360
Automatic Variables
User Defines
Built-in
Microsoft Confidential
361
PS C:\> $?
PS C:\> $HOME
PS C:\> $Host
PS C:\> $null
PS C:\> $PSHOME
PS C:\> $true
PS C:\> $false
362
Section 2: Kinds of
Variables
Lesson 2: User-Defined
Variables
Microsoft Confidential
363
User-Defined Variables
Created and maintained by user
Exist only in current session
Lost when session is closed
Microsoft Confidential
364
Variable Cmdlets
Name
Example
New-Variable
Clear-Variable
RemoveVariable
Set-Variable
Get-Variable
Microsoft Confidential
365
Constant Variables
Variables can only be made constant at creation (can not use =)
Can not be deleted
Can not be changed
Microsoft Confidential
366
ReadOnly Variables
Can not mark a variable ReadOnly with =
User Defines
Microsoft Confidential
367
Exampl
e:
UserDefine
d
Variabl
e
Name
---AeLookupSvc
ALG
AppIDSvc
Appinfo
DisplayName
----------Application
Application
Application
Application
Experience
Layer Gateway Service
Identity
Information
368
Microsoft Confidential
369
Microsoft Confidential
370
Example:
Literal
Strings
Create a variable
PS C:\> $a = 123
371
Lesson 2: Expandable
Strings
Microsoft Confidential
372
Example:
Expandabl
e Strings
Create a variable
PS C:\> $a = 123
373
Microsoft Confidential
374
Example:
Literal or
Expandabl
e String
Spanning
Multiple
Lines
Literal String
Expandable String
PS C:\> $lString
As
easy
as
$a
PS C:\> $eString
As
easy
as
123
375
Example:
Here
Strings
PS C:\> $lhere
As
' easy '
as
$a
PS C:\> $ehere
As
"easy"
as
123
376
Lesson 4: Variable
Sub-expression
Microsoft Confidential
377
Variable Sub-Expression
User Defines
Microsoft Confidential
378
Create a variable
PS C:\> $a = Get-Service -Name ALG
Example:
Variable
Subexpression
$(...)
Microsoft Confidential
380
Other Types
Alias
Full Name
Description
Object
System.Object
Boolean
System.Boolean
Char
System.Char
Int
System.Int32
-2147483648 to 2147483647
Long
System.Int64
-9223372036854775808 to
9223372036854775807
Double
System.Double
Enum
System.Enum
Array
System.Array
DateTime System.DateTim
e
Microsoft Confidential
381
Microsoft Confidential
382
Microsoft Confidential
383
Type Casting
384
Microsoft Confidential
385
Example:
Strong
Typing a
variable
386
Static Members
Static Member is callable without having to create an instance of a
type
Static Member is accessed by type name (not instance name)
::
Microsoft Confidential
387
Exampl
e:
Discove
r Static
Member
s
BaseType
-------System.ValueType
Example:
Print
ASCII
table
using
PowerSh
ell
33
34
35
36
37
38
39
=
=
=
=
=
=
=
Character:
Character:
Character:
Character:
Character:
Character:
Character:
!
"
#
$
%
&
'
389
Lesson 1: Type
Operators
Microsoft Confidential
390
Example
-is
-isNot
Microsoft Confidential
391
Example
-as
Same Result
PS C:\> [datetime]12/10/2013"
Friday, 27 December 2013 12:00:00 AM
Microsoft Confidential
392
Section 7: Parsing
Microsoft Confidential
393
Parsing Modes
Defines
User
PowerShell
parser divides commands into tokens
394
Example
2+2
Mode
Result
Expressi 4
on
Argume
nt
Expressi 4
on
$a = 2+2 ; $a
Expressi 4
on
Write-Output $a
Expressi 4
on
Write-Output $a/H
Argume
nt
Microsoft Confidential
"2+2"
"4/H"
395
Example:
Turn
Argument
Mode into
Expression
Mode with
$()
396
Example:
Turn
Expression
Mode into
Argument
Mode with
&
"Get-Process"
NPM(K)
PM(K)
WS(K) Id
------333
-----18
----8032
----- ----8.80
8244
413
39
155844
131.89
10140
84
1128
0.13
2228
Name
-----AcroRd32
AcroRd32
armsvc
397
Section 7: Parsing
Lesson 2: Escape
Character
Microsoft Confidential
398
Escape Character
Assigns a special interpretation to characters that follow
Backtick (grave accent)
ASCII 96
Microsoft Confidential
399
Exampl
es:
Backtick
Uses
Force a special
character to be
literal
PS C:\> $a = 123
PS C:\> Write-Host "`$a is $a"
$a is 123
Force a literal
character to be
special
here.
Line continuation
Must be last char
400
Special Characters
Character
`0
`a
`b
`f
`n
`r
`t
`v
Description
Note:
These characters are case-sensitive and
Null
only have effect within double quotes
Alert
Backspace
Form feed
New line
Carriage return
Horizontal tab
Vertical tab
Microsoft Confidential
Section 7: Parsing
Microsoft Confidential
402
Stop Parsing
Stops PowerShell from interpreting input
Use when entering external command arguments
(rather than escape characters)
Only takes effect until next newline or pipe character
--%
Microsoft Confidential
403
Example:
Stop
Parsing
External
Comman
d
Argument
s
Lab
Microsoft Confidential
405
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
406
Module Overview
Microsoft Confidential
407
408
Section 1: Arithmetic
Operators
Lesson 1: Arithmetic
Operators
Microsoft Confidential
409
Arithmetic Operators
Operato Description
r
Example(s)
Result(s)
Subtracts values
6 - 2
-6 + 2
-4
6 * 2
"ABC" * 3
12
ABCABCABC
Divides values
6/2
7%2
-shl
Shift-left bitwise
100 -shl 2
400
-shr
Shift-right
100 inbitwise
binary is 1100100
100 -shr 1
50
Microsoft Confidential
Section 2: Assignment
Operators
Lesson 1: Assignment
Operators
Microsoft Confidential
411
Assignment Operators
Operato Description
r
Example(s)
Sets variable
$integer = 100
+=
Increases variable
$integer += 1
-=
Decreases variable
$integer -= 1
*=
Multiplies variable
$integer *= 2
/=
Divides variable
$integer /= 2
%=
$integer %= 3
++
$integer++
--
$integer += 1
$integer++
Microsoft Confidential
412
Lesson 1: Binary
Operators
Microsoft Confidential
413
Binary Operators
Operator
Description
Example(s)
Binary Format
-bAnd
Bitwise AND
10 -band 3
1010 (10)
0011 (3)
-------- bAND
0010 (2)
-bOr
Bitwise OR
(inclusive)
10 -bor 3
1010 (10)
0011 (3)
--------1011 (11)
-bXor
Bitwise OR
(exclusive)
10 -bxor 3
1010 (10)
0011 (3)
------- bXOR
1001 (9)
-bNot
Bitwise NOT
-bnot 10
bOR
414
Microsoft Confidential
415
Split Operator
Description
Example(s)
PS C:\>
1
a
b
Note:
Example splits on space as delimiter
Binary split operator:
<string> -split <delimiter>
Note:
Example splits on comma as delimiter
416
Microsoft Confidential
417
Join Operator
Description
Example(s)
Microsoft Confidential
418
Lesson 3: Replace
Operator
Microsoft Confidential
419
Replace Operator
Description
Example(s)
Microsoft Confidential
420
Lesson 1: Format
Operator
Microsoft Confidential
421
Format Operator ( -f )
Formats strings by using the format method of string
objects
Format string on the left side of the operator
Objects to be formatted on the right side of the
operator
Format specifiers enable the value to take multiple
forms
Microsoft Confidential
422
Microsoft Confidential
424
-separated
Microsoft Confidential
425
Microsoft Confidential
426
Microsoft Confidential
427
Microsoft Confidential
428
Microsoft Confidential
429
Microsoft Confidential
430
Lab
Microsoft Confidential
431
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
432
Module Overview
Microsoft Confidential
433
Microsoft Confidential
434
Section 1: Array
Introduction
Microsoft Confidential
435
Index 0
Index 1
Index 2
Index 3
Index 4
Item 1
Item 2
Item 3
Item 4
Item 5
Microsoft Confidential
436
Lesson 1: Creating
Arrays
Microsoft Confidential
437
Example:
Creating
Arrays
438
Lesson 2: Accessing
Array Items
Microsoft Confidential
439
Example:
Accessing
Array
Items
PS C:\> $array
22
5
10
8
12
9
8
PS C:\> $array[0..2]
22
5
10
PS C:\> $array[0]
22
Last item in array using index
position
PS C:\> $array[-1]
8
440
Example:
Determin
e number
of items
in array
441
Microsoft Confidential
442
Example:
Adding
items to
an array
443
Microsoft Confidential
444
Example:
Sorting
Array
Display
445
Example:
Sorting
Array
446
Lesson 5: Modifying
Array Items
Microsoft Confidential
447
Example:
Manipulati
ng items in
an array
Manipulating items in an
array Using assignment
operator
PS C:\> $array[0] = 100
PS C:\> $array
100
8
8
9
10
12
22
999
Lesson 6: Determine
Array Object Members
Microsoft Confidential
449
Example:
Determine
array
object
members
MemberType
---------Method
Definition
---------int Compare
MemberType
--------------AliasProperty
Method
Definition
----------Count = Length
int
450
Lab
Microsoft Confidential
451
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
452
Module Overview
Microsoft Confidential
453
454
Microsoft Confidential
455
Microsoft Confidential
456
Microsoft Confidential
457
Example:
Creating
hash
tables
Value
----
-----
HV-SRV-1
192.168.1.1
458
Lesson 3: Accessing
Hash Table Items
Microsoft Confidential
461
Example:
Access
hash
tables
items
Name
---HV-SRV-1
Serial
Memory
Value
----192.168.1.1
THX1138
68719476736
Example:
Display
all hash
tables
keys
463
Example:
Display
all hash
tables
values
464
Lesson 4: Modifying
Hash Table Items
Microsoft Confidential
465
Microsoft Confidential
467
Example:
Sorting
hash
tables
Value
----4
{C, D, E}
192.168.1.1
68719476736
THX1138
468
Lesson 6: Searching
Hash Tables
Microsoft Confidential
469
Example:
Searchin
g hash
tables
PS C:\> $hash.ContainsValue(65467)
True
470
Microsoft Confidential
471
Example
:
Calculat
ed
Property
Size (KB)
--------950.50
94.91
Valu
e
Valu
e
Key
Exampl
e:
Custom
PSObje
ct
474
Exampl
e:
Custom
PSObje
ct
475
Section 3: Ordered
Dictionary
Lesson 1: Ordered
Dictionary
Microsoft Confidential
476
Ordered Dictionary
Alternative
to regular
hash tables
Works
similarly to a
hash table
but order is
preserved
Value
----Smith
John
Order not
preserved
Value
----John
Smith
Microsoft Confidential
Insertion order
preserved
477
Lab
Microsoft Confidential
478
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
479
Module Overview
Microsoft Confidential
480
Microsoft Confidential
481
Section 1: Looping
Microsoft Confidential
482
While
Conditional
Do While Conditional
Do Until
Conditional
For
Conditional
Foreach
Enumeratio
n
483
Section 1: Looping
Lesson 2: While
Microsoft Confidential
484
While Loop
Name Description
Example
While
$a = 0
While ($a lt 10) {$a; $a++}
Start
Is
Condition
True?
Yes
Run Code
No
End
Microsoft Confidential
485
Example
:
While
$ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Start-Sleep -Seconds 30
While (-not (Test-Connection -ComputerName $ComputerName -Quiet))
{
"Waiting on restart: $ComputerName"
Start-Sleep -Seconds 30
}
Waiting on restart: 2012R2-DC
Waiting on restart: 2012R2-DC
Waiting on restart: 2012R2-DC
PS C:\
PowerShell v3.0 RestartComputer introduced the Wait
parameter
Microsoft Confidential
486
Section 1: Looping
Lesson 3: Do While
Microsoft Confidential
488
Do While Loop
Name Description
Do
While
Example
Start
Run Code
Is
Condition
True?
No
End
Microsoft Confidential
489
Example
:
Do While
$ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Do
{
"Waiting on restart: $ComputerName"
Start-Sleep -Seconds 30
}
While (-not (Test-Connection -ComputerName $ComputerName -Quiet))
Waiting on restart: 2012R2-DC
Waiting on restart: 2012R2-DC
Waiting on restart: 2012R2-DC
PS C:\
PowerShell v3.0 RestartComputer introduced the Wait
parameter
Microsoft Confidential
490
Section 1: Looping
Lesson 4: Do Until
Microsoft Confidential
491
Do Until Loop
Nam
e
Description
Example
Do
Until
Start
Run Code
Is
Condition
True?
Yes
End
Microsoft Confidential
492
Example
:
Do Until
$ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Do
{
"Waiting on restart: $ComputerName"
Start-Sleep -Seconds 30
}
Until (Test-Connection -ComputerName $ComputerName -Quiet)
Waiting on restart: 2012R2-DC
Waiting on restart: 2012R2-DC
Waiting on restart: 2012R2-DC
PS C:\
PowerShell v3.0 RestartComputer introduced the Wait
parameter
Microsoft Confidential
493
Section 1: Looping
Lesson 5: For
Microsoft Confidential
494
For Loop
For
Syntax
Example
Start
Initialise
Is
Condition
True?
Yes
Run Code
Increment
No
End
Microsoft Confidential
495
Example
:
For
$Computers = @(Get-ADComputer -Filter {OperatingSystem -like "*server*"}).Name
For ($i=0 ; $i -lt $Computers.Length ; $i++)
{
"Computer $($i+1): $($Computers[$i])"
}
Computer 1: 2012R2-DC
Computer 2: 2012R2-MS
Microsoft Confidential
496
Section 1: Looping
Lesson 6: ForEach
Microsoft Confidential
498
ForEach Loop
ForEach
Syntax
Example
Start
Items in
Array?
Yes
Run Code
No
End
Microsoft Confidential
499
Example:
ForEach
Loop
$Services = Get-Service
'There are a total of ' + $Services.Count + ' services.'
ForEach ($Service in $Services)
{
$Service.Name + ' is ' + $Service.Status
}
There are a total of 167 services.
AeLookupSvc is Stopped
ALG is Stopped
AppIDSvc is Stopped
Appinfo is Stopped
AppMgmt is Stopped
AppReadiness is Stopped
AppXSvc is Stopped
AudioEndpointBuilder is Running
Audiosrv is Running
...
Microsoft Confidential
501
Section 2: Branching
Lesson 1: IF Statement
Microsoft Confidential
502
IF Statement
Branching structure
chooses which code to
run
If
Optional Elseif(s)
used for additional
test(s)
503
Option
al
If
Start
If (<test1>)
{
<statement list 1>
}
Is
condition
True?
Yes
No
End
Microsoft Confidential
504
If..Else
If (<test1>)
{
<statement list 1>
}
Else
{
<else statement list>
}
Start
Is
condition
True?
Yes
No
Run Else Statement
List
End
505
If..Elseif(s)
If (<test1>)
{
<statement list 1>
}
ElseIf (<test2>)
{
<statement list 2>
}
ElseIf (<test3>)
{
<statement list 3>
}
Start
Is first
condition
True?
Yes
Yes
Yes
No
Is second
condition
True?
No
No
Is third
condition
True?
No
End
Microsoft Confidential
506
Example:
If..ElseIf(s
)
Microsoft Confidential
507
If..ElseIf(s)..Else
If (<test1>)
{
<statement list 1>
}
ElseIf (<test2>)
{
<statement list 2>
}
Else
{
<else statement list>
}
Start
Is first
condition
True?
Yes
No
Is second
condition
True?
Yes
No
Run Else Statement
End
Microsoft Confidential
508
Example:
If..ElseIf..Else
Statement
$Language = (Get-CimInstance ClassName Win32_OperatingSystem).OSLanguage
if ($Language -eq "1033")
{
Write-Host "Language = English US" -ForegroundColor Magenta
}
elseif ($Language eq "1078")
{
Write-Host "Language = Afrikaans" -Foregroundcolor Green
}
else
{
Write-Host "Another Language" -ForegroundColor Cyan
}
509
Section 2: Branching
Microsoft Confidential
513
Switch
Like a simplified version of an If with ElseIfs
Called Select..Case in some other languages
Can process multiple test values, operates like a pipeline
Can accept file paths for process contents
Microsoft Confidential
514
Simple Switch
Start
Switch (<test-value>)
{
<condition 1> {<action 1>}
<condition 2> {<action 2>}
}
<testvalue>
-EQ
<condition
1>
True
Run <action
1>
True
Run <action
2>
False
$DomainRole = (Get-CimInstance -class
Win32_ComputerSystem).DomainRole
switch ($DomainRole)
{
0 {write-Host "standalone workstation"}
2 {write-Host "standalone server"}
}
<testvalue>
-EQ
<condition
2>
False
End
Microsoft Confidential
515
Section 2: Branching
Lesson 3: SWITCH
Statement
- Default Condition
Microsoft Confidential
520
Start
<testvalue>
-EQ
<condition
1>
Switch (<test-value>)
{
<condition 1> {<action 1>}
<condition 2> {<action 2>}
Default
{<action 3>}
}
True
Run <action
1>
True
Run <action
2>
True
Run <action
3>
False
<testvalue>
-EQ
<condition
2>
False
switch ($DomainRole)
{
0 {write-Host "standalone workstation"}
2 {write-Host "standalone server"}
Default {write-Host "other domain role"}
}
No
Conditions
Matched?
False
End
Microsoft Confidential
521
Section 2: Branching
Lesson 4: SWITCH
Statement
Multiple inputs
Microsoft Confidential
524
Switch
Multiple Values
Start
Process Value
<testvalue>
-EQ
<condition
1>
Switch (<test-value-array>)
{
<condition 1> {<action 1>}
Default
{<action 2>}
}
True
Run <action
1>
False
False
End
Microsoft Confidential
No
Conditions
Matched?
True
False
FalseAdditional
True
Values?
525
Run <action
2>
Example:
Switch with $_
526
Example:
SWITCH
Multiple
inputs
527
Section 2: Branching
Lesson 5: SWITCH
Statement
Case
Microsoft Confidential
528
Example:
SWITCH
Case-insensitive by default
switch ("HELLO")
{
"hello" {"lowercase"}
"HELLO" {"uppercase"}
}
lowercase
uppercase
529
Example:
SWITCH
Case
Sensitive
530
Section 2: Branching
Lesson 6: SWITCH
Statement
Wildcard
Microsoft Confidential
531
Example:
SWITCH
without
-Wildcard
Windows
532
Example:
SWITCH with
-Wildcard
Section 2: Branching
Lesson 7: SWITCH
Statement
Regex
Microsoft Confidential
534
Example:
SWITCH
with
-Regex
Section 2: Branching
Lesson 8: SWITCH
Statement Expression
Match
Microsoft Confidential
536
Example:
SWITCH
Expression
matches
537
Section 2: Branching
Lesson 9: SWITCH
Statement File
Processing
Microsoft Confidential
538
Example:
SWITCH
-File
539
Section 2: Branching
Microsoft Confidential
540
Microsoft Confidential
541
Lab
Microsoft Confidential
546
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
547
Module Overview
Microsoft Confidential
548
Microsoft Confidential
549
Section 1: Scope
Introduction
Microsoft Confidential
550
Microsoft Confidential
551
Microsoft Confidential
552
Scope Rules
Items are visible:
In scope where created & any child scope,
unless explicitly made private
Items are changed/created:
In current scope, unless scope overridden
Microsoft Confidential
553
Example:
Scopes
PS C:\> $Servername = 'Server01'
PS C:\> $Servername
Server01
Global Scope
Lifetime
Items cease to exist
when the scope
terminates
Script Scope
PS C:\> C:\script.ps1
Global (Original) Value: Server01
Local (Script) value: Server02
Local (in function) value SERVER02
New Local (Script) Value: Server02
PS C:\> $Servername
Server01
Function Scope
Visibility
Child scopes have
access to Parent
scope items
555
Microsoft Confidential
556
Scope Modifiers
[<scope-modifier>]:<name>
Scope Modifier Keywords
Global Highest level scope per host
Script Nearest Script Scope
Local Current Scope (Default)
Private Current Scope, unavailable to children
Microsoft Confidential
557
Example:
Change or create a variable in global scope from another
scope
$global:a = "one"
Microsoft Confidential
558
Microsoft Confidential
559
Exampl
e:
List
items
in a
scope
560
Microsoft Confidential
561
Dot-Source Notation
By default, child scope created when script or function runs
Dot-source does not create a child scope
Script or function runs in current scope and creates items in current
scope
Item visibility does not terminate with the script or function
Microsoft Confidential
562
Example
:
Dot
Source
Notation
Scripts
Notice space
between dot and
path
563
Example:
Dot
Source
Notation
Functions
PS C:\> C:\FunctionInScript.ps1
PS C:\> Get-ServerData -ComputerName 2012R2-DC
Get-ServerData : The term 'Get-ServerData' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try
again...
PS C:\> . C:\FunctionInScript.ps1
PS C:\> Get-ServerData -ComputerName 2012R2-DC
SystemDirectory Organization BuildNumber RegisteredUser
--------------- ------------ ----------- -------------C:\WINDOWS\s...
9600
administrator@
564
Section 4: Profiles
Lesson 1: Profiles
Microsoft Confidential
566
Microsoft Confidential
567
Profiles
Start PowerShell
Execute Profile
Scripts
Profile 1 - All Users, All Hosts
Profile 2 - All Users, Current Host
Profile 3 - Current User, All Hosts
Last run has
highest priority
Microsoft Confidential
568
$Profile
$Profile (automatic variable) holds expected path for all four profiles
Paths are relative to each host/computer
Profile must be created manually
Profiles Scopes:
Scope
Current User, Current
Host
Current User, All
Hosts
All Users, Current
Host
All Users, All Hosts
Name
$Profile or
$Profile.CurrentUserCurrentHost
$Profile.CurrentUserAllHosts
$Profile.AllUsersCurrentHost
$Profile.AllUsersAllHosts
Microsoft Confidential
569
Name
$Home\Documents\WindowsPowerShell\profile.ps1
$PsHome\profile.ps1
Microsoft Confidential
570
Name
$Home\Documents\WindowsPowerShell\Microsoft.PowerShellISE_pr
ofile.ps1
$PsHome\Microsoft.PowerShellISE_profile.ps1
Microsoft Confidential
571
Name
$Home\Documents\WindowsPowerShell\Microsoft.PowerShell_profil
e.ps1
$PsHome\Microsoft.PowerShell_profile.ps1
Microsoft Confidential
572
Example:
Listing
Profile
Paths
: C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
: C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.P
owerShellISE_profile.ps1
CurrentUserAllHosts
: C:\Users\Administrator\Documents\WindowsPowerShell\profile.
ps1
CurrentUserCurrentHost : C:\Users\Administrator\Documents\WindowsPowerShell\Microsof
t.PowerShellISE_profile.ps1
Length
: 81
573
574
Lab
Microsoft Confidential
575
Agenda
Module 1:
Introduction
Module 2:
Commands 1
Module 3: Pipeline 1
Module 4:
Commands 2
Module 5: Scripts
Module 6: Help
System
Module 7: Object
Models
Module 8: Operators
Microsoft Confidential
576
Module Overview
Microsoft Confidential
577
Microsoft Confidential
578
Section 1: Module
Introduction
Microsoft Confidential
579
Microsoft Confidential
580
Core Modules
PowerShell v4 only ships with core
modules
Many administrative cmdlets and
functions come from modules
provided with Windows and
applications
Windows 8, 8.1, Server 2012 and
Server 2012R2 include dozens of
modules and thousands of
commands
Module Name
Microsoft.PowerShell.Core
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
ISE
PSDesiredStateConfiguration
PSScheduledJob
PSWorkflow
PSWorkflowUtility
Microsoft Confidential
581
Section 1: Module
Introduction
Microsoft Confidential
582
Module Types
Module Code
Binary
Module
(.dll)
Script
Module
(.psm1)
Typically
compiled cmdlets
and providers
Typically scripted
functions
Dynamic
Module
Exists only in
memory, created onthe-fly
Holds proxy functions
for implicit remoting
583
Section 1: Module
Introduction
Microsoft Confidential
584
Version
------1.0.0.0
3.1.0.0
3.1.0.0
Name
---ISE
Microsoft.PowerShell.Ma...
Microsoft.PowerShell.Ut...
Microsoft Confidential
ExportedCommands
---------------{Get-IseSnipp...
{Add-Computer...
{Add-Member, ...
585
Module
Physical
Locations
Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules
ModuleType
---------Manifest
Manifest
...
Version
------1.0.0.0
1.0.0.0
Name
---ActiveDirectory
AppBackgroundTask
ExportedCommands
---------------{Add-ADCentralAccessPolicyMem...
{Disable-AppBackgroundTaskDia...
Microsoft Confidential
586
Microsoft Confidential
587
Import-Module
Adds one or more modules to current session
Import module by name
PS C:\> Import-Module -Name BitsTransfer
Microsoft Confidential
588
Remove-Module
Removes one or more modules from current session
Does not delete/uninstall module from computer
Microsoft Confidential
589
Section 1: Module
Introduction
Lesson 4: Module
Loading
Microsoft Confidential
590
Module Loading
PowerShell must import modules before using their functionality
Version 3.0+ automatically imports the module when a command is
used
Version 3.0+ searches for the command through all modules found in
$ENV:PSModulePath folders
Tab-completion and ISE Intellisense suggest every command in every
module installed to $ENV:PSModulePath folders
$PSModuleAutoloadingPreference = All | ModuleQualified | None
Microsoft Confidential
591
Exampl
e:
List
module
path
folders
PS v2.0+
Default
PS v4.0+
Default
592
Command Discovery
Get-Command (v3.0+) will return commands from imported and
available modules
Microsoft Confidential
593
Example:
GetCommand
Support
for
Modules
ModuleName
---------PSScheduledJob
Name ModuleName
-----------
---- ----------
Function
...
A:
594
Lesson 1: Creating a
Script Module
Microsoft Confidential
595
or
1. Create Module Folder in PSModule Path with
same name as .psm1, MyModule
2. Place MyModule.psm1 file in new folder
3. Import-Module MyModule
Microsoft Confidential
Lesson 2: Module
Manifest
Microsoft Confidential
598
MyModule
Microsoft Confidential
600
Module Scope
By default, modules are imported to the current scope
Modules can be imported to a specified scope using Import-Module
PS C:\> Get-Help Import-Module -Parameter scope
-Scope <String>
Imports the module only into the specified scope.
Valid values are:
-- Global: Available to all commands in the session.
Equivalent to the Global parameter.
-- Local: Available only in the current scope.
Microsoft Confidential
601
Lab
Microsoft Confidential
602
Microsoft Confidential
603
Pipeline
Microsoft Confidential
Click
to add
Clickicon
icon
to picture
add picture
Click icon to
Microsoft Confidential
607