Sie sind auf Seite 1von 561

Windows PowerShell v4.

0 for
the IT Professional
Part 1

Meet your trainer

<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

Module 11: Variables & Data


Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Microsoft Confidential

DAY 4

DAY
DAY 2

DAY
DAY 1
1

Agenda

Lab
Environmen
t

2012R2-DC

2012R2-MS

Windows Server 2012


R2
Core

Windows Server 2012


R2

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

Domain Name Contoso.com


Domain NetBIOS Name Contoso
Admin Account Username Administrator

User Account Username DanPark

Password PowerShell4

Password PowerShell4
Microsoft Confidential

Conditions and Terms of Use


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.

Copyright and Trademarks


2013 Microsoft Corporation. All rights reserved.

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

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

PowerShell default availability

Microsoft Confidential

Microsoft Confidential

16

Installing PowerShell versions


No
PowerSh
ell

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

PowerShell 4.0 in Server Core


Server Core starts in CMD Console upon local logon or RDP connection
ISE feature not available
PowerShell 2.0 Engine not enabled by default
Windows Server 2012R2

Installed by default

Windows Server 2012

Install Net 4.5 pre-requisite


Install Windows Management Framework 4.0

Windows Server 2008R2

Install .Net 4.5 pre-requisite


Install Windows Management Framework 4.0
Microsoft Confidential

19

Module 1: Introduction

Section 2: PowerShell
Features

Lesson 1: PowerShell
Hosts

Microsoft Confidential

20

Command-Line Interface (CLI)


Interactive mode
Simple commands to interact with applications and the operating
system
Handy shortcut keys: HOME, END, F7, arrows, CTRL+arrows

Microsoft Confidential

21

Integrated Scripting Environment (ISE)


Development Tool
Graphical Editor
Execution and Debugging

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

Anatomy of the ISE


PowerSh
ell tabs
Script
pane

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

Extended PowerShell Features


Covered in Windows PowerShell 4.0 for the IT Professional - Part 2

PowerShell Web Access

Windows PowerShell console hosted in IIS


Access the PowerShell console securely (HTTPS) through any browser from any OS
Targets a remote internal computer specified at sign-in

Microsoft Confidential

Microsoft Confidential

29

PSWA Browser Experience

Microsoft Confidential

32

Extended PowerShell Features


Covered in Windows PowerShell 4.0 for the IT Professional - Part 2

PowerShell Workflow

Affect multiple managed computers or devices at the same time


Sequences of long running tasks
Leverages Windows Workflow Foundation

Microsoft Confidential

Microsoft Confidential

34

Extended PowerShell Features


Covered in Windows PowerShell 4.0 for the IT Professional - Part 2

Desired State Configuration

Enables deploying and managing software configuration


Prevent configuration drift
Declaratively specify software environment

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

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

Stop-Service -Name Spooler -Force

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

PS C:\> Restart-Service Name Spooler -Verbose


143
12
1840
7320
76
0.22 11148 BDExtHost
...
VERBOSE: Performing the operation "Restart-Service" on target "Print
Spooler (Spooler)".
PS C:\> Test-Connection -ComputerName 2012R2-MS -Count 1 Quiet
True
Microsoft Confidential

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:\>

Get-Command Name Add-Computer Syntax

Add-Computer [-DomainName] <string> -Credential <pscredential> [-ComputerName


<string[]>] [-LocalCredential
<pscredential>] [-UnjoinDomainCredential <pscredential>] [-OUPath <string>] [Server <string>] [-Unsecure] [-Options
<JoinOptions>] [-Restart] [-PassThru] [-NewName <string>] [-Force] [-WhatIf] [Confirm] [<CommonParameters>]

Microsoft Confidential

57

Syntax Legend

Microsoft Confidential

58

Cmdlet Syntax - Command Name


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 Values>[]
Syntax Sample
PS C:\>

Get-Command Name Add-Computer Syntax

Add-Computer [-DomainName] <string> -Credential <pscredential> [-ComputerName


<string[]>] [-LocalCredential
<pscredential>] [-UnjoinDomainCredential <pscredential>] [-OUPath <string>] [Server <string>] [-Unsecure] [-Options
<JoinOptions>] [-Restart] [-PassThru] [-NewName <string>] [-Force] [-WhatIf] [Confirm] [<CommonParameters>]

Microsoft Confidential

59

Cmdlet Syntax - Required Parameter


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 Values>[]
Syntax Sample
PS C:\>

Get-Command Name Add-Computer Syntax

Add-Computer [-DomainName] <string> -Credential <pscredential> [-ComputerName


<string[]>] [-LocalCredential
<pscredential>] [-UnjoinDomainCredential <pscredential>] [-OUPath <string>] [Server <string>] [-Unsecure] [-Options
<JoinOptions>] [-Restart] [-PassThru] [-NewName <string>] [-Force] [-WhatIf] [Confirm] [<CommonParameters>]

Microsoft Confidential

60

Cmdlet Syntax - Optional Parameter and Value


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 Values>[]
Syntax Sample
PS C:\>

Get-Command Name Add-Computer Syntax

Add-Computer [-DomainName] <string> -Credential <pscredential> [-ComputerName


<string[]>] [-LocalCredential
<pscredential>] [-UnjoinDomainCredential <pscredential>] [-OUPath <string>] [Server <string>] [-Unsecure] [-Options
<JoinOptions>] [-Restart] [-PassThru] [-NewName <string>] [-Force] [-WhatIf] [Confirm] [<CommonParameters>]

Microsoft Confidential

61

Cmdlet Syntax - Switch Parameter


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 Values>[]
Syntax Sample
PS C:\>

Get-Command Name Add-Computer Syntax

Add-Computer [-DomainName] <string> -Credential <pscredential> [-ComputerName


<string[]>] [-LocalCredential
<pscredential>] [-UnjoinDomainCredential <pscredential>] [-OUPath <string>] [Server <string>] [-Unsecure] [-Options
<JoinOptions>] [-Restart] [-PassThru] [-NewName <string>] [-Force] [-WhatIf] [Confirm] [<CommonParameters>]

Microsoft Confidential

62

Cmdlet Syntax - Optional Parameter, Required


Syntax Definition
Value
<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 Values>[]
Syntax Sample
PS C:\>

Get-Command Name Add-Computer Syntax

Add-Computer [-DomainName] <string> -Credential <pscredential> [-ComputerName


<string[]>] [-LocalCredential
<pscredential>] [-UnjoinDomainCredential <pscredential>] [-OUPath <string>] [Server <string>] [-Unsecure] [-Options
<JoinOptions>] [-Restart] [-PassThru] [-NewName <string>] [-Force] [-WhatIf] [Confirm] [<CommonParameters>]

Microsoft Confidential

63

Cmdlet Syntax - Multiple Parameter Values


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 Values>[]
Syntax Sample
PS C:\>

Get-Command Name Add-Computer Syntax

Add-Computer [-DomainName] <string> -Credential <pscredential> [-ComputerName


<string[]>] [-LocalCredential
<pscredential>] [-UnjoinDomainCredential <pscredential>] [-OUPath <string>] [Server <string>] [-Unsecure] [-Options
<JoinOptions>] [-Restart] [-PassThru] [-NewName <string>] [-Force] [-WhatIf] [Confirm] [<CommonParameters>]

Microsoft Confidential

64

Cmdlet Syntax Diagram


Parameter Sets
PS C:\> Get-Command Name Stop-Process Syntax
Stop-Process [-Id] <int[]> [-PassThru] [-Force] [-WhatIf] [-Confirm]
[<CommonParameters>]
Stop-Process -Name <string[]> [-PassThru] [-Force] [-WhatIf] [-Confirm]
[<CommonParameters>]
Stop-Process [-InputObject] <Process[]> [-PassThru] [-Force] [-WhatIf]
[-Confirm] [<CommonParameters>]

Note: Name, InputObject and Id parameters cannot be used together


and are required (value only for -Id & -InputObject) in their respective
parameter set
Microsoft Confidential

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

Common Parameters (with alias in parenthesis)


-Debug (db)
-ErrorAction (ea)
-ErrorVariable (ev)
-OutVariable (ov)
-OutBuffer (ob)

Displays programmer-level detail


Determines how cmdlet responds to errors
Stores error messages in a specified variable
Stores output in a specified variable
Determines number of output objects to
accumulate in a buffer
Stores value of current pipeline* element as a
variable
Displays detailed information
Determines how cmdlet responds to warnings

-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

PS C:\> Restart-Service Name Netlogon


PS C:\>

Common
Parameter

PS C:\> Restart-Service Name Netlogon Verbose


VERBOSE: Performing the operation "Restart-Service" on target
"Netlogon (Netlogon)".
PS C:\>

Microsoft Confidential

69

Example:
Common
Parameter
s in Use ErrorAction

PS C:\> Get-Process Netlogon


Get-Process : Cannot find a process with the name "Netlogon".
Verify the process name and call the cmdlet again.
At line:1 char:1
+ Get-Process Netlogon
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo
: ObjectNotFound:
(Netlogon:String) [Get-Process], ProcessCommandException
PS C:\>
PS C:\> Get-Process Netlogon -ErrorAction SilentlyContinue
PS C:\>

Common Parameter
Microsoft Confidential

Error Action
70

Example:
Store
command
output in a
specified
variable
name

PS C:\> Get-FileHash .\iExploreProcesses.csv -OutVariable


csvhash
Common
Parameter

Use the variable to retrieve the command output


PS C:\> $csvhash
Algorithm

Hash

Path

-----------

----

----

Note:SHA256
$ prefix denotes
in PowerShell
6A78a variable
C:\iExploreProcesses.csv
Microsoft Confidential

71

Variabl
e
Name

Risk Mitigation Parameters


Many cmdlets also offer risk mitigation parameters
Typically when the cmdlet changes the system or application
-WhatIf
(wi)
-Confirm
(cf)

Displays message describing the effect of the command,


instead of executing the command
Prompts for confirmation before executing command

Microsoft Confidential

72

Example:
-WhatIf
Parameter
in use

PS C:\> Stop-Process -Name * -WhatIf


What
What
What
What
What
What

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

To complete a command, use either a:


Newline character (enter) , or a
Semi-colon

;
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

Semi-colon command termination


PS C:\>

Get-Service BITS ; Get-Process System

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

When a statement is not syntactically complete and there is a


newline character, PowerShell enters a line continuation

>>
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

Useful when line continuation is accidental (Ctrl-C followed by Up-Arrow gets


you back)

Microsoft Confidential

Microsoft Confidential

77

Example:
Line
Continuati
on

PS
>>
>>
>>
>>

C:\> "This is a multi-line


string that continues
on several lines
until the syntax is completed"

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

Section 2: Core Cmdlets

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:\>

Get-Command -Name *user*

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

PS C:\> Get-Command -Verb Get


CommandType
----------Alias
Alias
Function
...

Name
---Get-GPPermissions
Get-ProvisionedAppxPackage
Get-AppBackgroundTask

Microsoft Confidential

ModuleName
---------GroupPolicy
Dism
AppBackgroundTask

83

Exampl
e:
List
Cmdlet
s By
Noun

PS C:\> Get-Command -Noun Service


CommandType
----------Cmdlet
Cmdlet
Cmdlet
Cmdlet
...

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

PS C:\> Get-Command -CommandType Cmdlet


CommandType
----------Cmdlet
Cmdlet
...

Name
---Add-ADCentralAccessPolicyMember
Add-ADComputerServiceAccount

Microsoft Confidential

ModuleName
---------ActiveDirectory
ActiveDirectory

85

Example:
Single
Comman
d

PS C:\>

Get-Command -Name dir

CommandType
----------Alias

Name
---dir -> Get-ChildItem

Microsoft Confidential

ModuleName
----------

86

Example:
List
Cmdlet
syntax
with GetComman
d

PS C:\>

Get-Command Get-WinEvent -Syntax

Get-WinEvent [[-LogName] <string[]>] [-MaxEvents <long>]


[-ComputerName <string>] [-Credential <pscredential>]
[-FilterXPath <string>] [-Force] [-Oldest] [<CommonParameters>]
Get-WinEvent [-ListLog] <string[]> [-ComputerName <string>]
[-Credential <pscredential>] [-Force] [<CommonParameters>]
Get-WinEvent [-ListProvider] <string[]> [-ComputerName <string>]
[-Credential <pscredential>] [<CommonParameters>]
...

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

PS C:\> Get-Process -ComputerName 2012DC


-Name system -ErrorAction SilentlyContinue
Microsoft Confidential

88

Module 2: Commands 1

Section 2: Core Cmdlets

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

PS C:\> Get-Help Get-ChildItem


#or
PS C:\> Get-ChildItem -?
NAME
Get-ChildItem
SYNOPSIS
Gets the files and folders in a file system drive.
SYNTAX
Get-ChildItem [[-Path] <String[]>] [[-Filter] <String>]...
...
DESCRIPTION
The Get-ChildItem cmdlet gets the items in one or more...
...
RELATED LINKS
Online version: http://technet.microsoft.com/library/h...
...
REMARKS
To see the examples, type: "get-help Get-ChildItem ...
...

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

Default Help Sections (no


params)

All Help Sections (-Full)

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)

PS C:\> Get-Help Get-Counter -Parameter Counter


-Counter <String[]>
Gets data from the specified performance counters. Enter
one or more
...
Each counter path has the following format:
"[\\<ComputerName>]\<CounterSet>(<Instance>)\<CounterName>"
...
Required?
Position?
Default value
Accept pipeline input?
Accept wildcard characters?
Microsoft Confidential

false
1
true (ByValue, ByPropertyName)
True
93

Module 2: Commands 1

Section 3: Cmdlet Alternate


Names

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

Full cmdlet name


PS C:\> Get-ChildItem C:\Windows

Cmdlet Alias - Windows


PS C:\> dir C:\Windows

Cmdlet Alias - *nix


PS C:\> ls C:\Windows

Cmdlet Alias - PowerShell


PS C:\> gci C:\Windows

Microsoft Confidential

97

Module 2: Commands 1

Section 3: Cmdlet Alternate


Names

Lesson 2: User-defined
Aliases

Microsoft Confidential

98

Example:
Creating a
custom
alias

New Alias (list) for Get-ChildItem cmdlet


PS C:\> New-Alias -Name list -Value Get-ChildItem

Using New Alias (list)


PS C:\> list
Directory: C:\
Mode
---d---d-r-d-r-d----

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

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

Section 4: Pipeline Output


Format 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

Represented by a vertical bar character


Sends output from one command as input to another command (left
to right)
Passes Objects, not text
Allows Filtering, Formatting and Outputting
Cmdlets are designed to be chained together into pipelines
Microsoft Confidential

105

Module 3: Pipeline 1

Section 2: Pipeline Input

Lesson 1: Get Cmdlets


External Commands
Text File input

Microsoft Confidential

106

The Get Cmdlets


Typically placed first in the pipeline
Provides the input to be processed
Returns schedule
and bits services

PS C:\> Get-Service -Name Schedule , BITS | Start-Service

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

Text File Input


Text files provide input to be processed by the pipeline
Reads a
text file
PS C:\> Get-Content .\services.txt | Get-Service
Takes an action on
each line in the file

Microsoft Confidential

109

Import Cmdlets
Import structured text data into Windows PowerShell
Data can be processed by subsequent commands

PS C:\> Import-Csv Path .\usernames.csv Delimiter ;


Microsoft Confidential

110

Module 3: Pipeline 1

Section 3: Pipeline Object


Manipulation

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

Get all processes, Sort by virtual memory then Select top 2


PS C:\> Get-Process | Sort-Object VM -Descending |
Select-Object -First 2
Handles
------1283
1926

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

Get security event log then Group by entry type


PS C:\> Get-EventLog -LogName Security |
Group-Object EntryType
Count Name
----- ---18105 SuccessAudit
25 FailureAudit

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

Comparing text files


PS C:\> Get-Content -Path .\servers1.txt -OutVariable ref
PS C:\> Get-Content -Path .\servers2.txt -OutVariable diff
PS C:\> Compare-Object -ReferenceObject $ref -DifferenceObject $diff
InputObject SideIndicator
----------- ------------Server3

=>

Server3 is only in the difference variable


(servers2.txt)
Microsoft Confidential

116

Module 3: Pipeline 1

Section 4: Pipeline Output

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

Get-Process -Name powershell | Format-List


:
:
:
:

6400
472
0.78125
powershell

Microsoft Confidential

Output is in list format


Properties chosen are based on
default formatting in
PowerShell by object type

119

Example:
Format-List
with specific
properties

PS C:\> Get-Process -Name powershell |


Format-List -Property Name, BasePriority, PriorityClass

Name
: powershell
BasePriority : 8
PriorityClass : Normal

Microsoft Confidential

Output in list format


Consists of specified
properties

120

Example:
Format-Table
with default
properties

PS C:\> Get-Process | Format-Table


Handles

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

PS C:\> Get-Process | Format-Table -Property Name,Path,WorkingSet


Name
---armsvc
atieclxx
atiesrxx
audiodg
BDAppHost
BDExtHost
BDRuntimeHost
BingDesktop
CCC
...

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

Path truncated due to


wide values
Microsoft Confidential

124

Example:
Format-Table
with Auto Sized
Columns

PS C:\> Get-Process | Format-Table -Property Name,Path,WorkingSet -AutoSize


Name
---armsvc
atieclxx
atiesrxx
BDAppHost
BDExtHost
BDRuntimeHost
BingDesktop
CCC
...

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...

Path property truncation


is minimized with
Autosize, but
workingset column lost
Microsoft Confidential

125

PS C:\> Get-Process |
Format-Table -Property Name,Path,WorkingSet -AutoSize Wrap

Example:
Format-Table
with Wrap

Name
---armsvc
atieclxx
atiesrxx
BDAppHost

Path property is line


wrapped, workingset
still lost in this case

Path
----

C:\Program Files (x86)\Microsoft\BingDes


ktop\BDAppHost.exe
BDExtHost
C:\Program Files (x86)\Microsoft\BingDes
ktop\BDExtHost.exe
BDRuntimeHost C:\Program Files (x86)\Microsoft\BingDes
ktop\BDRuntimeHost.exe
BingDesktop
C:\Program Files (x86)\Microsoft\BingDes
ktop\BingDesktop.exe
CCC
C:\Program Files (x86)\ATI
Technologies\ATI.ACE\Core-Static\CCC.exe

Microsoft Confidential

126

Example:
Format-Table
with Grouping

PS C:\> Get-Process |
Sort-Object -Property BasePriority |
Format-Table -GroupBy BasePriority -Wrap -AutoSize

Processes are grouped by


BasePriority: 0
BasePriority (need to sort by

groupby prop first)


Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- ----------0
0
0
24
0
0 Idle
...
PS C:\> Get-EventLog -LogName Security | Group-Object
EntryType | Format-Table -AutoSize -Wrap

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

PS C:\> Get-ChildItem | Format-Wide


Directory: C:\
[PerfLogs]
[Program Files (x86)]
[Users]
[WPLUS_EULA]

[Program Files]
[PShell]
[Windows]

Output displayed in 2
columns by default

Microsoft Confidential

128

Example:
Format-Wide
Explicit number
of Columns

PS C:\> Get-ChildItem | Format-Wide -Column 3


Directory: C:\
[Intel]
[Program Files (x86)]

[PerfLogs]
[Users]

[Program Files]
[Windows]

Output displayed in 3
columns

Microsoft Confidential

129

Example:
Format-Wide
AutoSize
maximizes
columns

PS C:\> Get-Alias | Format-Wide -AutoSize


%
clc
cnsn
cvpa
echo
fc
gc
gjb

?
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

Section 4: Pipeline Output

Lesson 2: Export and


Import Cmdlets

Microsoft Confidential

131

Export Cmdlets
Export pipeline objects to text file
Should be last cmdlet on the pipeline

Microsoft Confidential

132

Example:
ExportClixml

PS C:\> get-acl C:\Process.txt -Audit |


Export-Clixml -Path fileacl.xml
PS C:\> notepad .\fileacl.xml

Microsoft Confidential

133

Example:
ExportCSV

PS C:\> Get-Service | Export-Csv c:\services.csv


PS C:\> notepad.exe C:\services.csv

-NoTypeInformation
parameter avoids
this as 1st line

Microsoft Confidential

134

Example:
ImportCsv

PS C:\> Import-Csv C:\usermailbox.csv | Select-Object


mailbox
Mailbox
------administrator@contoso.com
dpark@contoso.com
kakers@contoso.com

Microsoft Confidential

135

Module 3: Pipeline 1

Section 4: Pipeline Output

Lesson 3: Out Cmdlets

Microsoft Confidential

136

Out Cmdlets
Sends command output to a specified device
Name

Description

Out-Default

Sends output to default formatter and to default output cmdlet


(Out-Host)

Out-File

Sends output to a file


Append switch parameter
Encoding parameter allows control of the character encoding

OutGridView

Sends output to an interactive table in a separate GUI

Out-Host

Default
Sends output to PowerShell host
Paging switch parameter displays one page at a time

Out-Null

Deletes output instead of sending it down the pipeline

Out-Printer

Sends output to a printer

Out-String

Sends objects to the host as a series of strings


Microsoft Confidential

137

Example:
OutGridview

PS C:\> Get-Process | Out-GridView

Microsoft Confidential

138

Step 1: Send Get-Process output to Out-Gridview with


PassThru switch parameter, followed by export to CSV
Example:
OutGridview
with
PassThru

PS C:\> Get-Process | Out-GridView -PassThru |


Export-Csv c:\scripts\iExploreProcesses.csv
-NoTypeInformation

Step 2: Filter using


GUI. Click to select
output items

Step 3: View filtered output


in CSV

Microsoft Confidential

139

Module 3: Pipeline 1

Section 4: Pipeline Output

Lesson 4: Storing output


in a Variable

Microsoft Confidential

141

Storing Pipeline output in a Variable


Pipeline output can be stored in a user-defined variable using the =
assignment operator
Storing cmdlet output in a variable
PS C:\> $groupedEvents = Get-EventLog -LogName Security |
Group-Object EntryType

Accessing output using variable name and $ prefix


PS C:\> $groupedEvents | Format-Table -AutoSize
Count Name

Group

----- ----

----Microsoft Confidential

135950 SuccessAudit {System.Diagnostics.EventLogEntry...

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

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

Section 1: Script Blocks

Lesson 1: What is a
Script Block?

Microsoft Confidential

147

What is a Script Block?


A statement list in braces { }
Can accept parameter values and return output
Used by Cmdlets, Functions, Workflows and Desired State
Configuration
{<statement list>}
{
param ($parameter1,$parameterN)
<statement list>
}
Microsoft Confidential

148

Example:
Cmdlet
with
ScriptBloc
k
parameter
argument

PS C:\> Invoke-Command -ScriptBlock {Get-Process} ComputerName


>> 2012R2-DC, 2012R2-MS, WIN8-WS
Handles NPM(K)
------- -----4848
55
76
8
386
23
...

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

PS C:\> Measure-Command -Expression {Get-Process}


Days
Minutes
Seconds
Milliseconds
Ticks
...

:
:
:
:
:

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

Named Script Block


Reusable block of PowerShell code
Reduces size of code and increases reliability
Can accept parameter values and return output
Advanced Functions behave like Cmdlets
Can be created with help topics that can be used with Get-Help (like
cmdlets)
Microsoft Confidential

Microsoft Confidential

151

What does a Function Look Like?

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

A series of commands can be contained in a


function
PS C:\> Get-Service -Name spooler -RequiredServices
-ComputerName 2012R2DC

Run the function

PS C:\> Get-ServiceInfo
Microsoft Confidential

153

Example:
Creating a
utility
function with
parameters

A series of commands can be contained in a


function
Cmdlet parameter values become function
parameters

PS C:\> Get-ServiceInfo -svc spooler -computer


localhost

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

Native OS Remoting (-ComputerName


Parameter)
Typically Windows resource or action specific cmdlets
Use built-in Windows services
Target machines do not need PowerShell remoting
Examples:
PS C:\> Get-Command -ParameterName ComputerName
...
Get-Counter; Get-EventLog; Get-HotFix; Restart-Computer; Get-Process;
Get-Service; Stop-Computer; Test-Connection

Microsoft Confidential

159

What is PowerShell Remoting?


Introduced in Windows PowerShell 2.0 and enhanced in later versions
Windows PowerShell feature

Interactively run command(s) with a single remote computer


Run scriptblock or script on one or more remote computers
Temporary or Persistent Sessions (connections)
Destination can be restricted by limiting allowed commands and language
elements

PS C:\>

Interactive (1:1)
PS C:\>

Run Command(s) (1:Many)


Temporary or Persistent Session(s)
Microsoft Confidential

PS C:\>

160

Requirements
Local and Remote Computers:
PowerShell 2.0 or later (feature enhancements with newer
versions)

Remoting must be enabled:


Enabled by default on Windows Server 2012 Operating Systems
(OS) and later
Disabled by default on all Client and earlier Server OSs

Remote User Permissions:


Must be a member of the Local Administrator group on the remote
computer(s) (by default)
Microsoft Confidential

161

Enabling Remoting
Use local command or Group Policy

Start PowerShell with the "Run as administrator option


PS C:\> Enable-PSRemoting

Use group policy for bulk


configuration

Microsoft Confidential

162

Module 4: Commands 2

Section 3: Remoting

Lesson 2: Using
PowerShell Remoting

Microsoft Confidential

163

Example:
Interacti
ve
Session

PS C:\> Enter-PSSession -ComputerName 2012R2-DC


Remote
Computer

[2012R2-DC] PS C:\>
[2012R2-DC] PS C:\> Hostname
2012R2-DC

Ending a
session

[2012R2-DC] PS C:\> Exit-PSSession


PS C:\>

Local
Computer

165

Example:
Invoke a
command

PS C:\> Invoke-Command -ComputerName 2012R2-DC


>> -ScriptBlock {Get-Culture}
LCID
---3081

Name
---en-AU

DisplayName
----------English (Australia)

PSComputerName
-------------2012R2-DC

166

Example:
Invoke a
command
(1:many)

PS C:\> Invoke-Command -ComputerName 2012R2-DC, 2012R2-MS


>> -ScriptBlock {Get-Culture}
LCID
---1033
1033

Name
---en-US
en-US

DisplayName
----------English (United States)
English (United States)

PSComputerName
-------------2012R2-MS
2012R2-DC

167

Example:
Use
alternate
credential

PS C:\> Invoke-Command -ComputerName 2012R2-DC Credential


>> contoso\administrator -ScriptBlock {Get-Culture}
LCID
---3081

Name
---en-AU

DisplayName
----------English (Australia)

PSComputerName
-------------2012R2-DC

168

Example
:
Persiste
nt
Session
(repeat
use)

Step 1: Create a persistent session


PS C:\> New-PSSession -ComputerName 2012R2-DC OutVariable ps
Id Name
ComputerName State ConfigurationName
Availability
-- --------------- ----- ---------------------------1 Session1 2012R2-DC
Opened Microsoft.PowerShell Available

Step 2: Use the session


PS C:\> Invoke-Command Session $ps -ScriptBlock {Get-Culture}
LCID
---3081

Name
---en-AU

DisplayName
----------English (Australia)

PSComputerName
-------------2012R2-DC

169

Example
:
Persiste
nt
Session
(repeat
use)
1:many

Step 1: Create persistent sessions


PS C:\> New-PSSession -ComputerName 2012R2-DC, 2012R2-MS
OutVariable ps
Id
-1
2

Name
---Session1
Session2

ComputerName
-----------2012R2-DC
2012R2-MS

State
----Opened
Opened

ConfigurationName
----------------Microsoft.PowerShell
Microsoft.PowerShell

Availability
-----------Available
Available

Step 2: Use the sessions


PS C:\> Invoke-Command Session $ps -ScriptBlock {Get-Culture}
LCID

Name

DisplayName

PSComputerName

----

----

-----------

--------------

1033

en-US

English (United States)

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

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:

Be digitally signed for security


Take parameter values
Return values

Microsoft Confidential

176

Example:
Simple
script

Microsoft Confidential

177

Module 5: Scripts

Section 2: Running 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

PS C:\> Get-ExecutionPolicy List


Scope
----MachinePolicy
UserPolicy
Process
CurrentUser
LocalMachine

ExecutionPolicy
--------------Undefined
Undefined
Undefined
Undefined
RemoteSigned

Top most
takes
precedence

Effective
Policy
183

Example:
Set
Execution
Policy User

PS C:\> Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

Apply setting to current user


only, default is current
machine

184

Example:
Set
Execution
Policy Computer

Start PowerShell with the "Run as administrator option


PS C:\> Set-ExecutionPolicy -ExecutionPolicy Unrestricted

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

Section 2: Running Scripts

Lesson 2: Launching a
script

Microsoft Confidential

189

Running a
Script

Full path and file name


PS C:\> c:\scripts\script.ps1

Script in current directory


PS C:\Scripts> .\script.ps1

Spaces in path (tab completion helps)


PS C:\> & c:\scripts\my script.ps1

Script is in environment path


PS C:\> Script.ps1

Microsoft Confidential

190

Running a Script with the Mouse


Script files cannot be double clicked to run
Run with PowerShell option:
Right-click script
Select Run with
PowerShell

Microsoft Confidential

191

Launching a script from outside PowerShell


Optionally
(cmd.exe)
Keeps
PowerShell
Window open

Must be last parameter in


command

C:\> Powershell.exe -NoExit -File "c:\scripts\isecputime.ps1

Microsoft Confidential

192

Module 5: Scripts

Section 3: Script
Parameters

Lesson 1: The Param


Statement

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

PS C:\scripts> .\ScriptParamExample.ps1 -ComputerName localhost


True
PS C:\scripts> .\ScriptParamExample.ps1 -ComputerName DoesNotExist
False
PS C:\scripts>
Microsoft Confidential

194

Module 5: Scripts

Section 4: Script Comments

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

Section 4: Script Comments

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

#Requires -Version <N>[.<n>]

2.0+

#Requires -PSSnapin <PSSnapin-Name> [-Version <N>[.<n>]]

2.0+

#Requires -ShellId <ShellId>

2.0+

#Requires -Modules { <Module-Name> | <Hashtable> }

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.

Special comment tag: #Requires -Version <N>[.<n>]


Get-help About_Requires
Error when script run from PowerShell v2
Sample Script
#requires -Version 3
Get-ChildItem c:\ -Hidden

.\test.ps1 : The script 'test.ps1'cannot be run because it contained a


"# requires" statem ent at line 1 for W indow s Pow erShellversion 3.0.
The version required by the script does not m atch the currently
running version of W indow s Pow erShellversion 2.0.

Microsoft Confidential

200

Administrator Requirement
Script requires elevated user rights
o Script errors at start indicating
o Avoids unexpected errors in script

Special comment tag: #Requires -RunAsAdministrator


Error when script run from non-elevated session
Sample Script

#requires -RunAsAdministrator
Get-ChildItem c:\ -Hidden

.\RunAsAdm inTest.ps1 : The script 'RunAsAdm inTest.ps1'cannot


be run because it contains a "# requires" statem ent for
running as Adm inistrator.The current W indow s Pow erShell
session is not running as Adm inistrator.Start W indow s
Pow erShellby using the Run as Adm inistrator option,and then
try running the script again.

Microsoft Confidential

201

Module 5: Scripts

Section 5: Command
Precedence

Lesson 1: Explore
command precedence
rules

Microsoft Confidential

202

Command Lookup Precedence


PowerShell rules that determine which command to run when there is
more than one command with the same name

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

PS C:\> ping 2012r2-ms

Example:
Replace
another
command

Pinging 2012r2-ms.contoso.com [10.0.1.210] with 32 bytes of data:


Reply from 10.0.1.210: bytes=32 time<1ms TTL=128
Reply from 10.0.1.210: bytes=32 time<1ms TTL=128
Reply from 10.0.1.210: bytes=32 time<1ms TTL=128
Reply from 10.0.1.210: bytes=32 time<1ms TTL=128
Ping statistics for 10.0.1.210:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
PS C:\> New-Alias -Name ping -Value Test-Connection
PS C:\> ping 2012r2-ms

Ping now cmdlet


instead of
external
command

Source

Destination

IPV4Address

IPV6Address

------

-----------

-----------

-----------

WIN8-WS

2012r2-ms

10.0.1.210

WIN8-WS

2012r2-msMicrosoft Confidential10.0.1.210

204

#Run normal cmdlet


PS C:\> Get-Process system

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

#Create function with same name


PS C:\> Function Get-Process {"This isn't Get-Process"}
#Command precedence runs function instead of cmdlet
PS C:\> Get-Process
This isn't Get-Process
#Module qualify command name
PS C:\> Microsoft.PowerShell.Management\Get-Process -Name system
Handles
------1427

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

Enabling ISE on Servers


Not enabled by default
Manual Installation:
o Server Manager GUI, or Add-WindowsFeature cmdlet
ISE Command-Line Install Server 2012 and 2008R2 (From PS Console)
PS C:\> Import-Module ServerManager #Only needed on Server 2008R2
PS C:\> Get-WindowsFeature powershell*
Display Name
-----------[X] Windows PowerShell
[X] Windows PowerShell 3.0
[ ] Windows PowerShell 2.0 Engine
[ ] Windows PowerShell ISE

Name
------PowerShellRoot
PowerShell
PowerShell-V2
PowerShell-ISE

Install State
------------Installed
Installed
Available
Available

PS C:\> Add-WindowsFeature PowerShell-ISE


Success
------True

Restart
-------No

Needed Exit Code


---------------Success
Microsoft Confidential

Feature Result
---------------{Windows PowerShell ISE}
207

Launch ISE
Filename: powershell_ise.exe
Alias in PowerShell.exe: ISE

Launching ISE from PowerShell.exe


PS C:\> powershell_ise.exe
#or
PS> ISE
#or
PS> ISE $Profile

Microsoft Confidential

208

Integrated Context Sensitive Help


Context-Sensitive Help
Highlight text
Choose Help from menu or
Press F1

ISE Executes Get-Help


cmdlet
-ShowWindow parameter
used
Command executed visible in
Command pane

Microsoft Confidential

209

Auto-Save and Crash Recovery


Auto-Save
ISE automatically saves scripts to alternate location
Default save interval is 2 minutes
Interval is editable via menu and object model

Crash Recovery
Uses alternate auto-saved files to restore un-saved
scripts

Microsoft Confidential

210

Rich Copy to and from the ISE


Clipboard includes colors, font, size, etc.
Excellent feature for sharing code in email, pptx,
docx, etc.

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

Cmdlet or function parameters appear in a pop-out


window
Parameter value types shown in a secondary window

Microsoft Confidential

213

Example:
IntelliSense
Parameter
Arguments

Some cmdlet parameters display parameter


values

Microsoft Confidential

214

Syntax Color Highlighting


ISE includes enhanced syntax
highlighting
Color highlighting is automatic
and customizable
Tools-Options window (shown),
includes detailed token, stream,
and console colorization settings
Themes to make common color
sets easy to use
Microsoft Confidential

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+] )

Note: Subtle grey highlighting when cursor in front of


curly brace

Microsoft Confidential

217

ISE Code Snippets


Pre-created blocks of code
Inserted at cursor
Three kinds of snippets:
Default (included with ISEv3/4)
User-Defined
Module-Based

Keyboard Shortcut - Ctrl-J


Edit Menu, Start Snippets
Example on next slide

Microsoft Confidential

218

Example:
ISE Snippet
Insertion

Click Enter to choose snippet


and insert code

Ctrl-J
or
Edit -> Start
Snippets
Microsoft Confidential

219

ISE Compiled Add-Ons


Compiled add-ons allow for rich
functionality to be created, such a variable
watch window
Compiled add-ons are WPF-based controls
The built-in Show-Command Add-On is a
good example of a compiled add-on
Look for compiled add-ons coming from the
PowerShell community and informally from
Microsoft

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

222

Module 6: Help System

Module Overview

Microsoft Confidential

223

Module 6: Help System


Section 1: Beyond Cmdlet Help
Getting help for PowerShell concepts

Section 2: Managing the Help System


Updatable Help

Section 3: More Help System Usage


Using Help
Comment-based help topics for functions and scripts

Microsoft Confidential

224

Module 6: Help System

Section 1: Beyond Cmdlet


help

Lesson 1: Getting help


for PowerShell concepts

Microsoft Confidential

225

Example:
Concept
help in the
console

Conceptual help topic names start with about_


PS C:\> Get-Help about_
Name

Category Module Synopsis

----

-------- ------ --------

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

1. Type Get-Help about_ in the console pane


2. Click on an item in the result set
3. Press F1

2
3

Microsoft Confidential

227

Module 6: Help System

Section 2: Managing the


help system

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)

Help is updated per Module:


o
o
o
o

Help readily updated by authors


No need to ship updates with Service Packs or new module download
Module authors designate URL for help download in module manifest
Module author provides web site URL targets

Note: PowerShell Modules will be discussed later.


Microsoft Confidential

229

Update-Help Diagram (Internet Connected)

Help
e
t
a
Upd

Internet

Update-Help
Upd
ate-

Help

Microsoft Confidential

230

Updatable Help With Internet Access


Automatically downloads Help content for Cmdlets and modules in
current session (including discoverable modules)
Only downloads updated help topics
For system modules, administrative elevation required
o Run PS window as admin, then run update-help

Only updates Help once per day even if run multiple times
o -Force can be used to update each time

HelpinfoURI property of modules indicates URL for download


Microsoft Confidential

231

Update-Help Diagram (Not Internet Connected)


Internal
Folder
Location

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

Updatable Help No Internet Access


Save-Help cmdlet saves help files locally for later use:
o On computer with Internet Access:

PS C:\> Save-Help DestinationPath \\SomeServer\SomeShare

o On computers without Internet Access (no GPO source path):


PS C:\> Update-Help SourcePath \\SomeServer\SomeShare

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

Updatable Help Modules


Update-Help can be targeted at individual modules
Update-Help Module ModuleName
Update-Help Module *
Get-Module ActiveDirectory | Update-Help

Note: Modules are discussed in a later module.

Microsoft Confidential

234

Module 6: Help System

Section 3: Using the help


system

Lesson 1: Using Help

Microsoft Confidential

235

Get-Help -ShowWindow
Display Help in floating
window

PowerShell Help Window


PS C:\> Get-Help -ShowWindow

Cmdlet-specific Help Window


PS C:\> Get-Help Get-Process -ShowWindow
Microsoft Confidential

236

Module 6: Help System

Section 3: Using the help


system

Lesson 2: Commentbased help topics for


functions and scripts

Microsoft Confidential

237

Function/Script Comment-based Help


Special help comment keywords can be used to write GetHelp topics for functions and scripts
Syntax
# .< help keyword>
# <help content>
-or <#
.< help keyword>
< help content>
#>
Microsoft Confidential

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

PS C:\> Get-Help .\ScriptHelpExample.ps1 Full


NAME
C:\scripts\ScriptHelpExample.ps1
SYNOPSIS
Script returns the most recent system event log entries.
SYNTAX
C:\scripts\ScriptHelpExample.ps1 [[-Log] <Object>] [[-NumberOfEvents]
<Object>] [<CommonParameters>]
...
Microsoft Confidential

241

Module 6: Help System

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

243

Module 7: Object
Models

Module Overview

Microsoft Confidential

244

Module 7: Object Models


Section 1: Objects in PowerShell
What is an object?
Identify PROPERTIES and METHODS for an object
Identify the TYPE of an object

Section 2: Object Models


Where do TYPES come from?
ISE IntelliSense and Member Completion

Microsoft Confidential

245

Module 7: Object Models

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

Type: Object Template

Bike
Size Property
Colour Property
Brake() Method
Wheelie() Method

Object: Instances of a type

$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

Module 7: Object Models

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

PS C:\> Get-ChildItem c:\windows\windowsupdate.log | Get-Member


TypeName: System.IO.FileInfo
Name
---AppendText
Create
CreateText
Decrypt
Delete
...
Attributes
CreationTime
CreationTimeUtc
Directory
...

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

PS C:\> Get-ChildItem c:\windows\windowsupdate.log | Get-Member


TypeName: System.IO.FileInfo
Name
---AppendText
Create
CreateText
Decrypt
Delete
...
Attributes
CreationTime
CreationTimeUtc
Directory
...

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)

Object stored in a variable


PS C:\> $csvhash = Get-FileHash .\iExploreProcesses.csv

Microsoft Confidential

256

Example:
Retrieving
Property
using dot
notation
(Variable)

Pipe variable to Get-Member to list properties


PS C:\>

$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...

Dot (.) followed by the property name


PS C:\>

$csvhash.Hash

207267C4B159E53C2272E6574DD89C78CF83648133698D793AB727D8CDF9
Microsoft Confidential

257

Example:
Retrieving
Property
using dot
notation
(Command)

Object property can also be accessed using parenthesis


PS C:\> (Get-FileHash .\iExploreProcesses.csv) | Get-Member
TypeName: Microsoft.Powershell.Utility.FileHash
Name
---Equals

MemberType
---------Method

Definition
---------bool Equals(System.Object obj)

GetHashCode Method

int GetHashCode()

GetType

Method

type GetType()

ToString

Method

string ToString()

Dot (.) followed by the property name


Algorithm

NoteProperty System.String Algorithm=SHA256

PS C:\> (Get-FileHash .\iExploreProcesses.csv).Hash

Hash
NoteProperty System.String Hash=207...
207267C4B159E53C2272E6574DD89C78CF83648133698D793AB727D8CDF9
Microsoft Confidential

258

Exampl
e:
Call
method
on an
object

PS C:\> (Get-Process -Name spoolsv) | Get-Member -MemberType Method


TypeName: System.Diagnostics.Process
Name
MemberType
------------BeginErrorReadLine
Method
BeginOutputReadLine
Method
CancelErrorRead
Method
CancelOutputRead
Method
Close
Method
CloseMainWindow
Method
CreateObjRef
Method
Dispose
Method
Kill
Method
...

Definition
---------void BeginErrorReadLine()
void BeginOutputReadLine()
void CancelErrorRead()
void CancelOutputRead()
void Close()
bool CloseMainWindow()
System.Runtime...
void Dispose(),
void Kill()

Dot (.) followed by the method name, followed by parenthesis


PS C:\> (Get-Process -Name spoolsv).Kill()
Microsoft Confidential

259

Module 7: Object Models

Section 1: Objects in
PowerShell

Lesson 3: Identify the


TYPE of an object

Microsoft Confidential

260

Example 1:
Find the object
TYPE returned by
the
Get-Date cmdlet

PS C:\> Get-Date | Get-Member


TypeName: System.DateTime
Name
---Add
AddDays
AddHours

MemberType
---------Method
Method
Method

Definition
---------datetime Add(timespan value)
datetime AddDays(double value)
datetime AddHours(double value)

Get-Member displays the TYPE name

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

GetType() METHOD retrieves the TYPE name


Available on ALL objects in PowerShell

Microsoft Confidential

262

Module 7: Object Models

Section 2: Object Models

Lesson 1: Where do
TYPES come from?

Microsoft Confidential

263

Where do TYPES come from?


OBJECT MODELS

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)

PowerShell works with all of these OBJECT MODELS and more!

Microsoft Confidential

264

Module 7: Object Models

Section 2: Object Models

Lesson 2: ISE
IntelliSense and Member
Completion

Microsoft Confidential

266

Pop-out window shows object members


Example:
IntelliSense
Object Members

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

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

Comparison Operators - Basic


No Wildcards
Equals
eq
Not Equals
ne
-gt Greater Than

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

PS C:\> 'PowerShell' -gt 'CMDPrompt'


True
PS C:\> 'a' lt 'aa'
True
PS C:\> $service = Get-Service bits
PS C:\> $service.Status -eq 'Running'
True

Microsoft Confidential

276

Comparison Operators - Wildcards


-like
Equals with wildcards
Not Equals with
notlik wildcards
e

-clike
cnotlik
Casee
Sensitive
Sensitive
Version

Allowed Wildcards
*

Zero or any number of any


chars

Exactly one of any char

[1az9] Exactly one of given char(s)


[a-l]

Exactly one of range of given


char(s)

Microsoft Confidential

277

Example:
-Like

PS C:\> 'Pear' -eq 'p*'


False
PS C:\> 'Pear' -like 'p*'
True
PS C:\> $Process = Get-Process -Name Sys*
PS C:\> $Process
Handles NPM(K)

PM(K) WS(K) VM(M) CPU(s) Id ProcessName

------- ------

----- ----- ----- ------ -- -----------

724

8972

628

13 51.33

PS C:\> $Process.Name -like '???????*'


False
Microsoft Confidential

4 System
Must be 7 chars
followed by zero or
278
more

Comparison Operators Regular Expressions


See Get-Help about_Regular_Expressions

-match

Regular Expression
comparison
Regular Expression NOT
notmatc comparison
h

Microsoft Confidential

-cmatch
Casecnotmat
Sensitive
ch Version

279

Example:
-Match

PS C:\> 'Digit 5 in this string' -match '\d'


True
PS C:\> 'hello there' -match '^there'
False
\d - Digit
^ - Start of Text

See Get-Help about_Regular_Expressions for syntax

Microsoft Confidential

280

Comparison Operators Array/Collection


Containment
CaseAlways results in Boolean (True/False)

Sensitive
Version

Array on left, Singleton on Right

-contains Array Contains single


Array not Contains
notcontai single
ns

-ccontains
cnotcontai
ns

Singleton on left, Array on Right

-in
-notin

Single in Array
Single not in Array

-cin
-cnotin

-in, -notin introduced by PowerShell v3.0

Microsoft Confidential

CaseSensitive
281
Version

Example:
Array
Containment

PS C:\> 1,2,3 -contains 2


True
PS C:\> "a","b","c" -notcontains a"
False
PS C:\> 2 -in 1,2,3
True
PS C:\> "a" -notin "a","b","c"
False

Microsoft Confidential

282

Example:
Array
Containment

PS C:\> (Get-Process).Name -contains 'Notepad'


True
PS C:\> $ServerList = Get-Content .\textfile.txt
PS C:\> $ServerList -contains 'Server10'
True
PS C:\> 'Server20' -in $ServerList
True

Microsoft Confidential

283

Example:
Operator
Case
Sensitivity

PS C:\> "abcde" -eq "ABCDE"


True
PS C:\> "abcde" -ceq "ABCDE"
False
PS C:\> "abcde" -like "ABC*"
True
PS C:\> "abcde" -clike "ABC*"
False
PS C:\> "abcde" -match ABCDE$"
True
PS C:\> "abcde" -cmatch ABCDE$"
False
Microsoft Confidential

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

TRUE only when both statements are TRUE.

-or

TRUE when either or both statements are TRUE.

-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

PS C:\> (4 lt 8) and (5 lt 10)


True
PS C:\> (4 lt 8) or
True

(5 lt 4)

PS C:\> (4 lt 8) xor (5 lt 10)


False
PS C:\> -not (4 lt 8)
False
PS C:\> -not (Test-Path C:\Windows)
False

Microsoft Confidential

287

Module 8: Operators 1

Section 3: Range Operators

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

Range of Characters Operator


Alphabetical [<letter>-<letter>]
Used with Like,-NotLike and Parameters that accept wildcards
PS C:\> Get-ChildItem C:\windows\System32\[a-d]*
Directory: C:\windows\System32
Mode
LastWriteTime
---------------d---22/08/2013 11:36 AM
AdvancedInstallers

Length Name
------ ----

d----

20/05/2014

8:22 AM

AppLocker

d----

19/10/2013

8:19 AM

appmgmt

Microsoft Confidential

290

Specified Characters Operator


Alphabetical [<letter><letter>]
Used with Like,-NotLike and Parameters that accept wildcards
PS C:\> Get-ChildItem C:\windows\System32\[jz]*
Directory: C:\windows\System32
Mode
---d---d----a---a---a---a--...

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

Numeric Byte Multipliers


Convenient byte multiples
Commonly-used powers of 2
Case-insensitive
Multiplier
Meaning
kb
kilobyte (n * 1024)
mb
gb
tb
pb

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

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

Section 1: Pipeline Objects

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

Section 2: Pipeline Cmdlets

Lesson 1: More Object


Cmdlets

Microsoft Confidential

300

Other Object Cmdlets


ForEachObject

Performs an operation against each item.


Aliases:
%
ForEach

Where-Object Filters objects in the pipeline


Aliases:
?
Where

Microsoft Confidential

301

Example:
ForEachObject

Take an action on each object


PS C:\> Get-Service net* | ForEach-Object {"Hello " + $_.Name}
Hello
Hello
Hello
Hello

Netlogon
Netman
netprofm
NetTcpPortSharing

Microsoft Confidential

302

Example:
Pipeline
Filtering
with WhereObject

PS C:\> Get-ChildItem -path *.txt |


Where-Object {$_.length -gt 10kb} |
Sort-Object -property Length |
Format-Table -property name, length

Get-ChildItem -path *.txt

Where-Object {$_.length -gt


10kb}

Sort-Object -property Length

Format-Table -property name,


length

(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+

Simplified filtering syntax


Syntax emulates natural language
PowerShell v3.0+
Note: Multiple filter conditions need full syntax

PS C:\> Get-ChildItem | Where-Object { $_.Length gt 1MB }


PS C:\> Get-ChildItem | Where-Object { $_.PSIsContainer }
PS C:\> Get-Service | Where-Object {$_.Status -eq "Running" and $_.CanShutdown}

PowerShell v3.0+ (Single comparison operator only)


PS C:\> Get-ChildItem | Where-Object Length -gt 1MB
PS C:\> Get-ChildItem | Where PSIsContainer
PS C:\> Get-Service
| Where Status -eq Running

Microsoft Confidential

No compound
conditions with
simplified syntax
304

Example:
Filtering with
Parameters vs.
Where-Object

Filter output with Where-Object (~11 milliseconds)


PS C:\> Get-Process |
Where-Object {$_.Name -eq "explorer"}

Filter output with parameters (~4 milliseconds)


PS C:\> Get-Process -Name explorer

PowerShell Proverb: Filter left. Format Right.

Microsoft Confidential

305

Retrieve single property from collection without using


ForEach-Object

Example:
Automatic
Member
Enumeration

Single level
PS C:\> (Get-Process).ID
4300
8844
8812

Doesnt work in
PowerShell v1.0 and
v2.0

Multiple levels deep


PS C:\> (Get-EventLog Log System).TimeWritten.DayOfWeek |
>> Group-Object
Count
----4174
4349

Name
---Tuesday
Monday

Group
----{Tuesday, Tuesday, Tuesday...}
{Monday, Monday, Monday...}
Microsoft Confidential

306

Module 9: Pipeline 2

Section 3: Pipeline
Processing

Lesson 1: Begin, Process


and End Blocks

Microsoft Confidential

307

Foreach-Object -Process Parameter


ForEach-Object often used with positional parameter in
simple scenario
PS C:\> Get-EventLog -LogName Application -Newest 5 |
ForEach-Object {$_.Message | Out-File -Filepath Events.txt -Append}
Position 1 is -Process
Parameter

PS C:\> Get-EventLog -LogName Application -Newest 5 |


ForEach-Object -Process {$_.Message | Out-File Events.txt -Append}
Parameter can be
named
Microsoft Confidential

308

Begin, Process and End Parameters


ForEach-Object cmdlet supports Begin, Process and End
Parameters
Begin block run once before any items are processed
Process block run for each object on pipeline
End block run once after all items have been processed
PS C:\> Get-EventLog -LogName Application -Newest 5 |
ForEach-Object
-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}

Microsoft Confidential

309

Begin, Process and End Parameters


ForEach-Object cmdlet supports Begin, Process and End
Parameters
Begin block run once before any items are processed
Process block run for each object on pipeline
End block run once after all items have been processed
PS C:\> Get-EventLog -LogName Application -Newest 5 |
ForEach-Object
-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}

Microsoft Confidential

310

Begin, Process and End Parameters


ForEach-Object cmdlet supports Begin, Process and End
Parameters
Begin block run once before any items are processed
Process block run for each object on pipeline
End block run once after all items have been processed
PS C:\> Get-EventLog -LogName Application -Newest 5 |
ForEach-Object
-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}

Microsoft Confidential

311

Named Blocks in Functions/ScriptBlocks


Statements can be in an unnamed block or in one or more named blocks
Allows custom processing of collections coming from pipelines
Can be defined in any order
Begin Block

o Statements executed once, before first pipeline object

Process Block

o Statements executed for each pipeline object delivered


o If a collection of zero elements is sent via the pipeline, the process block is not executed at
all.
o If called outside a pipeline context, block is executed exactly once

End block

o Statements executed once, after last pipeline object


o Default if unnamed
Microsoft Confidential

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
}
}

PS C:\> Get-EventLog -LogName Application -Newest 5 | My-Function


Microsoft Confidential

313

Module 9: Pipeline 2

Section 4: Cmdlet
Parameter Pipeline Input

Lesson 1: Two ways to


accept pipeline input

Microsoft Confidential

314

Methods Of Accepting Paramater Pipeline Input


User Defines

Cmdlet parameters can accept pipeline input in one of two


ways:
ByValue
(Object Data Type)
ByPropertyName (Object Property Name)
Cmdlet parameters may accept pipelined objects by value,
by property name or both.

Microsoft Confidential

315

Does a Parameter Accept Pipeline Input?


UserPS
Defines
C:\> Get-Help Restart-Computer -Parameter ComputerName

-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

Pipeline Input ByValue


For parameters that accept pipeline input ByValue,
piped objects will bind:
To a parameter of the same TYPE
To a parameter that can be converted to the same TYPE

Microsoft Confidential

317

Restart-Computer ComputerName Parameter


Example:
Pipeline
Input
ByValue

PS C:\> Get-Help Restart-Computer -Parameter ComputerName


-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

Pipe Computer names (strings) to Restart-Computer


PS C:\> '2012R2-MS','2012R2-DC' | Restart-Computer WhatIf
What if: Performing the operation "Restart the computer." on target "2012R2-MS".
What if: Performing the operation "Restart the computer." on target "2012R2-DC".

319

Pipeline Input ByPropertyName


For parameters that accept pipeline input
ByPropertyName,
piped objects properties will bind:
To parameter(s) of the same name

Microsoft Confidential

320

Restart-Computer ComputerName Parameter


Example:
Pipeline
Input
ByProper
ty

PS C:\> Get-Help Restart-Computer -Parameter ComputerName


-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

Pipe Computer names (column in CSV) to Restart-Computer


PS C:\> Import-Csv .\ServerInfo.csv |
Restart-Computer WhatIf
What if: Performing the operation "Restart the computer." on target "2012R2-DC".
What if: Performing the operation "Restart the computer." on target "2012R2-MS".
321

The Parameter Binding Steps


User Defines

1.
2.
3.
4.
5.
6.

Bind
Bind
Bind
Bind
Bind
Bind

all named parameters


all positional parameters
from the pipeline by value
from the pipeline by value
from the pipeline by name
from the pipeline by name

Microsoft Confidential

with exact match


with conversion
with exact type match
with type conversion

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

325

Module 10: Providers

Module Overview

Microsoft Confidential

326

Module 10: Providers


Section 1: Providers Introduction
What are Providers?
Section 2: Built-in Providers
Built-in Providers

Section 3: Provider Cmdlets


Provider Cmdlet

Microsoft Confidential

327

Module 10: Providers

Section 1: Providers
Introduction

Lesson 1: What are


Providers?

Microsoft Confidential

328

What are PowerShell Providers?


Define the logic to access, navigate and edit a data store
Functionally resemble a file system hierarchy
Common interface to different data stores

Microsoft Confidential

329

Where to get Providers


PowerShell ships with built-in providers
Providers can imported via module
Examples of well-known imported providers:

Active Directory
SQL Server

Microsoft Confidential

330

What is a PowerShell Drive?


A specific entry-point to a data store surfaced by a provider
Allows any data store to be exposed like a file system, as if
it were a mounted drive
Classic file system volume naming convention <Drive
Name>:
Consistent drive interaction with common Cmdlets

Microsoft Confidential

331

Module 10: Providers

Section 2: Built-in Providers

Lesson 1: Built-in
Providers

Microsoft Confidential

332

Built-in Providers
Provider

Drive

Data Store

Alias

Alias:

Windows PowerShell aliases

Certificate

Cert:

x509 certificates for digital signatures

Environment

Env:

Windows environment variables

FileSystem

C:, D:, etc. *

File system drives, directories, and files

Function

Function:

Windows PowerShell functions

Registry

HKLM:, HKCU:

Windows registry

Variable

Variable:

Windows PowerShell variables

WSMan

WSMan:

WS-Management configuration
information

* FileSystem drives can vary on each system

Microsoft Confidential

333

Module 10: Providers

Section 3: Provider Cmdlets

Lesson 1: Provider
Cmdlets

Microsoft Confidential

334

Example:
GetPSProvider

Returns a table of installed providers, their capabilities and


drives
PS C:\> Get-PSProvider
Name
---Alias
Environment
FileSystem
Function
Registry
Variable
Certificate
WSMan

Capabilities
-----------ShouldProcess
ShouldProcess
Filter, ShouldProcess, Credentials
ShouldProcess
ShouldProcess, Transactions
ShouldProcess
ShouldProcess
Credentials

Drives
-----{Alias}
{Env}
{C}
{Function}
{HKLM, HKCU}
{Variable}
{Cert}
{WSMan}

335

Module 10: Providers

Section 3: Provider Cmdlets

Lesson 2: Drive Cmdlets

Microsoft Confidential

337

Example:
GetPSDrive

Returns drives in current session


PS C:\> Get-PSDrive
Name
---Alias
C
Cert
Env
Function
HKCU
HKLM
Variable
WSMan

Used (GB) Free (GB) Provider


--------- --------- -------Alias
206.81
16.00
FileSystem
Certificate
Environment
Function
Registry
Registry
Variable
WSMan

Root
---C:\
\
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE

338

Example:
New-PSDrive
RemovePSDrive

Creates a user-defined drive


PS C:\> New-PSDrive -Name HKCR -PSProvider Registry
-Root HKEY_CLASSES_ROOT

Creates a user-defined drive (use only single letter name


with persist)
PS C:\> New-PSDrive -Name H -PSProvider FileSystem
-Root \\2012R2-MS\HomeShare -Persist
-Credential (Get-Credential Contoso\DanPark)

Removes a PowerShell drive (user or built-in)


PS C:\> Remove-PSDrive -Name HKCR

339

Module 10: Providers

Section 3: Provider Cmdlets

Lesson 3: Item Cmdlets

Microsoft Confidential

340

Item Cmdlets
Name

Example

Get-Item

PS C:\> (Get-Item c:\Windows).LastAccessTime

Get-ChildItem

PS C:\> Get-ChildItem -Path C:\Windows

Copy-Item

PS C:\> Copy-Item c:\Logs -Destination d:\Logs Recurse

Move-Item

PS C:\> Move-Item HKLM:\software\A\* HKLM:\software

Clear-Item

PS C:\> Clear-Item HKLM:\Software\MyCompany Confirm

Microsoft Confidential

341

Item Cmdlets
Name

Example

RemoveItem

PS C:\> Get-ChildItem * -Include *.mp3 -Recurse |


Remove-Item

Set-Item

PS C:\> Set-Item -Path env:UserRole -Value Administrator

Invoke-Item PS C:\> Invoke-Item d:\Documents\Users.xls"


New-Item

PS C:\> New-Item -ItemType file -Path d:\test.txt",


"c:\Logs\test.log"

RenameItem

PS C:\> Rename-Item HKLM:\Software\Company -NewName


Marketing

Microsoft Confidential

342

Module 10: Providers

Section 3: Provider Cmdlets

Lesson 4: ItemProperty
Cmdlets

Microsoft Confidential

343

ItemProperty Cmdlets
Name

Example

GetItemProperty

PS C:\> Get-ItemProperty -Path


HKLM:\SOFTWARE\Microsoft\PowerShell\1

CopyItemProperty

PS C:\> Copy-ItemProperty -Path MyApp -Destination


HKLM:\Software\MyAppRev2 -Name MyProperty

MoveItemProperty

PS C:\> Move-ItemProperty HKLM:\Software\MyCompany\MyApp


-Name Version -Destination
HKLM:\Software\MyCompany\NewApp

ClearItemProperty

PS C:\> Clear-ItemProperty -Path


HKLM:\Software\MyCompany\MyApp -Name Options

Microsoft Confidential

344

ItemProperty Cmdlets
Name

Example

RemoveItemProperty

PS C:\> Remove-ItemProperty -Path HKLM:\Software\MyApp


-Name MyProperty

Set-ItemProperty

PS C:\> Get-ChildItem weekly.log |


Set-ItemProperty -Name IsReadOnly -Value $true

New-ItemProperty

PS C:\> Get-Item -Path HKLM:\Software\MyCompany |


New-ItemProperty -Name NoOfLocations -Value 3

RenameItemProperty

PS C:\> Rename-ItemProperty -Path HKLM:\Software\MyApp


-Name config -NewName oldconfig

Microsoft Confidential

345

Module 10: Providers

Section 3: Provider Cmdlets

Lesson 5: Content
Cmdlets

Microsoft Confidential

346

Content Cmdlets
Name

Example

Get-Content PS C:\> Get-Content C:\Logs\Log060912.txt -TotalCount 50


PS C:\> Get-Content Env:\CommonProgramFiles
PS C:\> Get-Content Function:\Get-IseSnippet
AddContent

PS C:\> Get-Content test.xml |


Add-Content final.xml -Force -Encoding UTF8

ClearContent

PS C:\> Clear-Content C:\Windows\Logs\bpa\Reports\*


-Include 2013* -Exclude 2014*

Set-Content PS C:\> Get-Date | Set-Content C:\Output\date.csv

Microsoft Confidential

347

Module 10: Providers

Section 3: Provider Cmdlets

Lesson 6: Location
Cmdlets

Microsoft Confidential

348

Location Cmdlets
Name

Example

GetLocation

PS C:\> Get-Location
C:\

SetLocation

PS C:\> Set-Location -Path HKLM:\SOFTWARE


PS HKLM:\SOFTWARE>

Microsoft Confidential

349

Module 10: Providers

Section 3: Provider Cmdlets

Lesson 7: Path Cmdlets

Microsoft Confidential

350

Path Cmdlets
Name

Example

Test-Path

PS C:\> Test-Path $pshome\PowerShell.exe -NewerThan "July


13, 2009
True

Join-Path

PS C:\> Join-Path -Path C: -ChildPath Temp Resolve


C:\Temp

Split-Path

PS C:\> Split-Path -Path 'C:\Program Files (x86)\Internet


Explorer\iexplore.exe' Leaf
iexplore.exe

Microsoft Confidential

351

Path Cmdlets
Name

Example

ConvertPath

PS C:\> Convert-Path HKLM:\software\Microsoft


HKEY_LOCAL_MACHINE\Software\Microsoft

ResolvePath

PS C:\> Resolve-Path c:\prog* -Relative


..\..\Program Files
..\..\Program Files (x86)

Microsoft Confidential

352

Variable syntax access PSDrive items


Drive

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

Module 10: Providers

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

355

Module 11: Variables


and Data Types

Module Overview

Microsoft Confidential

356

Module 11: Variables and Data Types


Section 1: Variables
What are variables?
Section 2: Kinds of variables
Automatic Variables
User-Defined Variables

Section 3: String Type


Literal Strings
Expandable Strings
Here Strings
Variable Sub-Expression

Microsoft Confidential

357

Module 11: Variables and


Data Types

Section 1: Variables

Lesson 1: What are


Variables?

Microsoft Confidential

358

What are variables?


Unit of memory
Defined and accessed using a dollar sign prefix ($)
Holds object or collection of objects
Variable names can include spaces and special characters
Not case-sensitive
Kinds of variables:
o Automatic (built-in)
o User-defined
Microsoft Confidential

359

Module 11: Variables and


Data Types

Section 2: Kinds of
Variables

Lesson 1: Automatic
Variables

Microsoft Confidential

360

Automatic Variables
User Defines

Built-in

Created and maintained by PowerShell


Store PowerShell state

Microsoft Confidential

361

Automatic Variable Examples


Get-Help about_Automatic_Variables
PS C:\> $Error

List of all errors

PS C:\> $?

Execution status of last operation

PS C:\> $HOME

Users home directory

PS C:\> $Host

Current host application for PowerShell

PS C:\> $null

NULL or empty value

PS C:\> $PSHOME
PS C:\> $true

Full path of installation directory for


PowerShell
Represents TRUE in commands

PS C:\> $false

Represent FALSE in commands


Microsoft Confidential

362

Module 11: Variables and


Data Types

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

PS C:\> New-Variable zipcode -Value 98033

Clear-Variable

PS C:\> Clear-Variable -Name Processes

RemoveVariable

PS C:\> Remove-Variable -Name Smp

Set-Variable

PS C:\> Set-Variable -Name desc -Value "Description"

Get-Variable

PS C:\> Get-Variable -Name m*

Microsoft Confidential

365

Constant Variables
Variables can only be made constant at creation (can not use =)
Can not be deleted
Can not be changed

PS C:\> New-Variable -Name pi -Value 3.1415926 -Option Constant

Microsoft Confidential

366

ReadOnly Variables
Can not mark a variable ReadOnly with =
User Defines

Can not be easily deleted (must use Remove-Variable with -Force)


Can not be changed with = (must use Set-Variable with -Force)

PS C:\> New-Variable -Name max -Value 256 -Option ReadOnly

Microsoft Confidential

367

Exampl
e:
UserDefine
d
Variabl
e

PS C:\> $svcs = Get-Service


#or
PS C:\> Get-Service -OutVariable svcs
#or
PS C:\> New-Variable -Name svcs -Value (Get-Service)
PS C:\> $svcs
Status
-----Stopped
Stopped
Running
Running
...

Name
---AeLookupSvc
ALG
AppIDSvc
Appinfo

DisplayName
----------Application
Application
Application
Application

Experience
Layer Gateway Service
Identity
Information
368

Variables and Data Types


Remember, in PowerShell:
Everything is an OBJECT
Each OBJECT has a TYPE
Variables reference OBJECTS

Microsoft Confidential

369

Module 11: Variables and


Data Types

Section 3: String Type

Lesson 1: Literal Strings

Microsoft Confidential

370

Example:
Literal
Strings

Create a variable
PS C:\> $a = 123

Include the variable in a literal string (single-quotes)


PS C:\> $b = 'As easy as $a'

Notice that $a is not expanded


PS C:\> $b
As easy as $a

371

Module 11: Variables and


Data Types

Section 3: String Type

Lesson 2: Expandable
Strings

Microsoft Confidential

372

Example:
Expandabl
e Strings

Create a variable
PS C:\> $a = 123

Include the variable in an expandable string (doublequotes)


PS C:\> $b = "As easy as $a"

Notice that $a is expanded


PS C:\> $b
As easy as 123

373

Module 11: Variables and


Data Types

Section 3: String Type

Lesson 3: Here Strings

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
$a
"

PS C:\> $lString
As
easy
as
$a

PS C:\> $eString
As
easy
as
123

375

Example:
Here
Strings

Simplify use of longer, more complex string


assignments
Here String can contain quotes, @ sign, etc.
Literal Here String
Expandable Here String
PS C:\> $lhere = @'
As
'easy'
as
$a
'@

PS C:\> $ehere = @"


As
"easy"
as
$a
"@

PS C:\> $lhere
As
' easy '
as
$a

PS C:\> $ehere
As
"easy"
as
123
376

Module 11: Variables and


Data Types

Section 3: String Type

Lesson 4: Variable
Sub-expression

Microsoft Confidential

377

Variable Sub-Expression
User Defines

Returns the result of one or more enclosed statements


Can be used to access an object property and concatenate
its value within an expandable string

Microsoft Confidential

378

Create a variable
PS C:\> $a = Get-Service -Name ALG

Example:
Variable
Subexpression
$(...)

Determine the variable type


PS C:\> $a.GetType().FullName
System.ServiceProcess.ServiceController

Use variable in a string Returns the type


PS C:\> Write-Host "service: $a"
service: System.ServiceProcess.ServiceController

Try to use a property of the variable in a string The property is


not expanded
PS C:\> Write-Host "service: $a.name"
service: System.ServiceProcess.ServiceController.name

Create a variable sub-expression that includes the property


PS C:\> Write-Host "service: $($a.name)"
service: ALG
379

Module 11: Variables and


Data Types

Section 4: Other Types

Lesson 1: Other types

Microsoft Confidential

380

Other Types
Alias

Full Name

Description

Object

System.Object

Every type in PowerShell is derived from object

Boolean

System.Boolean

$true and $false

Char

System.Char

Stores UTF-16-encoded 16-bit Unicode code point

Int

System.Int32

-2147483648 to 2147483647

Long

System.Int64

-9223372036854775808 to
9223372036854775807

Double

System.Double

Double-precision floating-point number

Enum

System.Enum

Defines a set of named constants

Array

System.Array

One or more dimensions with 0 or more elements

DateTime System.DateTim
e

Stores date and time values

Microsoft Confidential

381

Module 11: Variables and


Data Types

Section 5: Using Types

Lesson 1: Using types

Microsoft Confidential

382

What object type am I using?


PowerShell typically picks object type

Examples of PowerShell choosing appropriate Type


PS C:\> (1024).GetType().FullName
System.Int32
PS C:\> (1.6).GetType().FullName
System.Double
PS C:\> (1tb).GetType().FullName
System.Int64

Microsoft Confidential

383

Type Casting

You can control object types


[ Square Brackets ] in front of an object will force that type
In the brackets use any valid object type name
Some common types have simpler type alias
Examples of Type Casting
PS C:\> [system.int32]1.6
2
PS C:\> $MyNumber = [int]"000123"
PS C:\> $MyNumber
123
PS C:\> $MyNumber.GetType().FullName
System.Int32
Microsoft Confidential

384

Variables can be Strongly Typed


Variables are weakly typed by default
Type cast the variable name during creation to strongly type
Variable will only hold that type of object

Weakly Typed Variable

Strongly Typed Variable

PS C:\> $var1 = [int]1.3


PS C:\> $var1
1

PS C:\> [int]$var1 = 1.3


PS C:\> $var1
1

PS C:\> $var1 = 1.2


PS C:\> $var1
1.2

PS C:\> $var1 = 1.2


PS C:\> $var1
1

Microsoft Confidential

385

Example:
Strong
Typing a
variable

PS C:\> [int]$var1 = 123.5


PS C:\> $var1
124
PS C:\> [string]$var2 = 987.6
PS C:\> $var2
987.6
PS C:\> $var1.GetType().FullName ; $var2.GetType().FullName
System.Int32
System.String
PS C:\> $var1 = "Fred"
Cannot convert value "Fred" to type "System.Int32".
Error: "Input string was not in a correct format."

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)

::

Static Members are accessed using the Static Operator

Microsoft Confidential

387

A type can be used in PowerShell using square brackets


PS C:\> [char]

Exampl
e:
Discove
r Static
Member
s

IsPublic IsSerial Name


-------- -------- ---True
True
Char

BaseType
-------System.ValueType

Use Get-Member -Static to discover useful members


PS C:\> [char] | Get-Member -Static

Get-Member without -Static discovers members that provide


information about the type
PS C:\> [char] | Get-Member

Calling a STATIC member


PS C:\> [char]::IsWhiteSpace(" ")
True
388

Example:
Print
ASCII
table
using
PowerSh
ell

Use range operator and Char type to convert numbers to


ASCII Characters
PS C:\> 33..255 | ForEach-Object {
Write-Host "Decimal: $_ = Character: $([Char]$_)"
}
Decimal:
Decimal:
Decimal:
Decimal:
Decimal:
Decimal:
Decimal:
...

33
34
35
36
37
38
39

=
=
=
=
=
=
=

Character:
Character:
Character:
Character:
Character:
Character:
Character:

!
"
#
$
%
&
'

389

Module 11: Variables and


Data Types

Section 6: Type Operators

Lesson 1: Type
Operators

Microsoft Confidential

390

Type Operators Test Object Types


Operator

Example

-is

PS C:\> (get-date) -is [DateTime]


True

-isNot

PS C:\> (get-date) -isNot [DateTime]


False

Microsoft Confidential

391

Type Operators Type Cast via Operator


Operator

Example

-as

PS C:\> 12/10/2013" -as [datetime]


Friday, 27 December 2013 12:00:00 AM

Same Result
PS C:\> [datetime]12/10/2013"
Friday, 27 December 2013 12:00:00 AM

Microsoft Confidential

392

Module 11: Variables and


Data Types

Section 7: Parsing

Lesson 1: Parsing Modes

Microsoft Confidential

393

Parsing Modes
Defines
User
PowerShell
parser divides commands into tokens

Parser is in either EXPRESSION or ARGUMENT mode


depending on the token
In expression mode, the parsing is conventional: strings
must be quoted, numbers are always numbers, and so on.
In argument mode, numbers are treated as numbers but
all other arguments are treated as strings unless they start
with $, @, ', ", or (.
Microsoft Confidential

394

Parsing Mode Examples


User Defines

Example
2+2

Mode
Result
Expressi 4
on

Write-Output InputObject 2+2

Argume
nt

Write-Output InputObject (2+2)

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
$()

Get-Date is a token interpreted as an ARGUMENT by the


parser
Get-Date is not treated as an expression
PS C:\> Write-Host "The date is: Get-Date"
The date is: Get-Date
$ changes the parsing mode to EXPRESSION
PS C:\> Write-Host "The date is: $(Get-Date)"
The date is: 1/3/2013 11:03:53

396

Example:
Turn
Expression
Mode into
Argument
Mode with
&

Store a string representing a Cmdlet name in a variable


Call the command by using the ampersand (&) character
PS C:\> $cmd =
PS C:\> $cmd
Get-Process

"Get-Process"

PS C:\> & $cmd


Handles

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

Module 11: Variables and


Data Types

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

PS C:\> Write-Host "There are two


line breaks`n`nhere. "
There are two line breaks

Limited List (next


slide)

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

Module 11: Variables and


Data Types

Section 7: Parsing

Lesson 3: Stop 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

Parsing and special characters can make external


commands challenging
PS C:\> icacls X:\VMS /grant Dom\HVAdmin:(CI)F
CI : The term 'CI' is not recognized as the name of
a cmdlet, function, script file, or operable
Parenthesis cause
program.
issue
Use --% to stop PowerShell parsing
PS C:\> icacls X:\VMS --% /grant Dom\HVAdmin:(CI)F

Sends the following command to the icacls program


X:\VMS /grant Dom\HVAdmin:(CI)F
404

Module 11: Variables


and Data Types

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

406

Module 12: Operators 2

Module Overview

Microsoft Confidential

407

Module 12: Operators 2


Section 1: Arithmetic Operators

Section 2: Assignment Operators

Section 3: Binary Operators

Section 4: Split, Join, and Replace Operators


Split Operator
Join Operator
Microsoft Confidential

408

Module 12: Operators 2

Section 1: Arithmetic
Operators

Lesson 1: Arithmetic
Operators

Microsoft Confidential

409

Arithmetic Operators
Operato Description
r

Example(s)

Result(s)

Adds integers; concatenates strings, arrays, 6 + 2


8
and hash tables
"file" + "name" filename

Subtracts values

6 - 2

Indicates negative value

-6 + 2

-4

Multiplies integers; copies strings and


arrays

6 * 2
"ABC" * 3

12
ABCABCABC

Divides values

6/2

Returns remainder of division (modulus)

7%2

-shl

Shift-left bitwise

100 -shl 2

400

-shr

Shift-right
100 inbitwise
binary is 1100100

100 -shr 1

50

-shl shifts digits n chars


left
400 in binary is
110010000

Microsoft Confidential

100 in binary is 1100100


-shr shifts digits n chars
right
50 in binary is 110010
410

Module 12: Operators 2

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

%=

Divides variable and assigns remainder to


variable

$integer %= 3

++

Unary Operator. Increases variable by 1

$integer++

--

Unary Operator. Decreases variable


by 1= $integer$integer-$integer
+ 1
All produce same
result

$integer += 1
$integer++

Microsoft Confidential

412

Module 12: Operators 2

Section 3: Binary Operators

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

0000 1010 (10)


---------------- bNOT
1111 0101 (-11)
Microsoft Confidential

bOR

414

Module 12: Operators 2

Section 4: Split, Join &


Replace Operators

Lesson 1: Split Operator

Microsoft Confidential

415

Split Operator
Description

Example(s)

Unary split operator:


-split <string>

PS C:\>
1
a
b

Note:
Example splits on space as delimiter
Binary split operator:
<string> -split <delimiter>

-split "1 a b"

PS C:\> "1,a b" -split ","


1
a b

Note:
Example splits on comma as delimiter

The -Split operator uses a Regular


Expression for the delimiters
Microsoft Confidential

416

Module 12: Operators 2

Section 4: Split, Join &


Replace Operators

Lesson 2: Join Operator

Microsoft Confidential

417

Join Operator
Description

Example(s)

Unary join operator:


-join <string[]>

PS C:\> -join ("a", "b", "c")


abc

Binary join operator:


String[]>
-Join<Delimiter>

PS C:\> "Windows", "PowerShell", "4.0" join


[char]2
WindowsPowerShell4.0
PS C:\> "How","are","you","doing?" -join " "
How are you doing?

Microsoft Confidential

418

Module 12: Operators 2

Section 4: Split, Join &


Replace Operators

Lesson 3: Replace
Operator

Microsoft Confidential

419

Replace Operator
Description

Example(s)

Binary replace operator:


<String[]> -Replace
<Delimiter>

PS C:\> "Windows PowerShell 4.0" replace "4.0","5.0"


Windows PowerShell 5.0

Microsoft Confidential

420

Module 12: Operators 2

Section 5: Format Operator

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

Format Operator Index Example


Index Positions
Ordered using
index

PS C:\> "{1}{0}{2}{0}{3}{0}{4}" -f "-","Text","separated","with","dash


Text-separated-with-dash

index[ ,alignment ][ :formatString ] } f string(s) , to be formatted

Microsoft Confidential

424

Format Operator Alignment Example


Forced Width
(negative-left justified, positive-right
justified)

PS C:\> "{1}{0,5}{2}" -f "-","Text","separated","with","dash


Text

-separated

ex[ ,alignment ][ :formatString ] } f string(s) , to be form

Microsoft Confidential

425

Format Operator FormatString Example 1


Format as
percentage

PS C:\> "{0:p} {1:p} {2:p}" -f 0.3,0.56,0.99


30.00% 56.00% 99.00%

ex[ ,alignment ][ :formatString ] } f string(s) , to be form

Microsoft Confidential

426

Format Operator FormatString Example 2


Format as
percentage with 0
decimal points

PS C:\> "{0:p0} {1:p1} {2:p2}" -f 0.3,0.566,0.991


30% 56.6% 99.10%

ex[ ,alignment ][ :formatString ] } f string(s) , to be form

Microsoft Confidential

427

Format Operator FormatString Example 3


Round number to
2 decimal places

PS C:\> "{0:n2}" -f 3.1415926


3.14

ex[ ,alignment ][ :formatString ] } f string(s) , to be form

Microsoft Confidential

428

Format Operator FormatString Example 4


Format as local
computer
currency

PS C:\> '{0:c} {1:c} {2:c}' -f 100.67,34,1340.78


$100.67 $34.00 $1,340.78

ex[ ,alignment ][ :formatString ] } f string(s) , to be form

Microsoft Confidential

429

Format Operator FormatString Example 5


Format
DateTime
PS C:\> '{0:hh}:{0:mm}:{0:ss}' -f (get-date)
11:35:16

ex[ ,alignment ][ :formatString ] } f string(s) , to be form

Microsoft Confidential

430

Module 12: Operators 2

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

432

Module 13: Arrays

Module Overview

Microsoft Confidential

433

Module 13: Arrays


Section 1: Array Introduction
What Are Arrays?
Section 2: Using Arrays
Creating Arrays
Accessing Array Items
Adding Array Items
Sorting Arrays
Modifying Array Items
Determine Array Object Members

Microsoft Confidential

434

Module 13: Arrays

Section 1: Array
Introduction

Lesson 1: What Are


Arrays?

Microsoft Confidential

435

What are arrays?

Data structure storing a collection of items


Each item is in its own compartment
Items can be the same type or different types
Items can be accessed using index positions:

Index 0

Index 1

Index 2

Index 3

Index 4

Item 1

Item 2

Item 3

Item 4

Item 5

Microsoft Confidential

436

Module 13: Arrays

Section 2: Using Arrays

Lesson 1: Creating
Arrays

Microsoft Confidential

437

Example:
Creating
Arrays

Arrays can be created in a number of ways:


Cmdlets that return multiple items
PS C:\> $processarray = Get-Process
Assigning multiple values to a variable
PS C:\> $array = 22,5,10,8,12,9,8
Array sub-expression operator
PS C:\> $b = @()

438

Module 13: Arrays

Section 2: Using Arrays

Lesson 2: Accessing
Array Items

Microsoft Confidential

439

Example:
Accessing
Array
Items

Display all items in an array

Display first 3 items in array

PS C:\> $array
22
5
10
8
12
9
8

PS C:\> $array[0..2]
22
5
10

First item in array using index


position

Display first item and last item in


array
PS C:\> $array[0,-1]
22
8

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

Determine the number of items in an array


PS C:\> $array.Count
7
PS C:\> $array.Length
7

441

Module 13: Arrays

Section 2: Using Arrays

Lesson 3: Adding Array


Items

Microsoft Confidential

442

Example:
Adding
items to
an array

Adding items to an array


PS C:\> $array += 999
PS C:\> $array
22
5
10
8
12
9
8
999

443

Module 13: Arrays

Section 2: Using Arrays

Lesson 4: Sorting Arrays

Microsoft Confidential

444

Example:
Sorting
Array
Display

Sort-Object only sorts the console output Array order is


not changed
PS C:\> $array | Sort-Object Descending
999
22
12
10
9
8
8
5

445

Example:
Sorting
Array

Array Type Static Method Sort changes item order


PS C:\> [array]::Sort($myarray)
PS C:\> $myarray
5
8
8
9
10
12
22
999

446

Module 13: Arrays

Section 2: Using Arrays

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

Manipulating items in an array


Using array method
PS C:\> $array.Set(0,200)
PS C:\> $array
200
8
8
9
10
12
22
999
448

Module 13: Arrays

Section 2: Using Arrays

Lesson 6: Determine
Array Object Members

Microsoft Confidential

449

Example:
Determine
array
object
members

Piping to Get-Member discovers item members Not array


members
PS C:\> $array | Get-Member
TypeName: System.Int32
Name
---CompareTo

MemberType
---------Method

Definition
---------int Compare

Use Get-Member Inputobject parameter to get array members


PS C:\> Get-Member -InputObject $array
TypeName: System.Object[]
Name
------Count
Add

MemberType
--------------AliasProperty
Method

Definition
----------Count = Length
int
450

Module 13: Arrays

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

452

Module 14: Hash Tables

Module Overview

Microsoft Confidential

453

Module 14: Hash Tables


Section 1: Hash Table Introduction
What are Hash Tables?
Creating Hash Tables
Accessing Hash Table Items
Modifying Hash Table Items
Sorting Hash Tables
Section 2: Hash Table Use Cases
Hash Table Examples
Section 3: Ordered Dictionary
Ordered Dictionary
Microsoft Confidential

454

Module 14: Hash Tables

Section 1: Hash Table


Introduction

Lesson 1: What are Hash


Tables

Microsoft Confidential

455

What are hash tables?


Dictionary array form
Stores one or more key(name)/value pairs
Access value using corresponding key
Key must be unique
Efficient for retrieving data constant search time
Get-Help about_Hash_Tables

Microsoft Confidential

456

Module 14: Hash Tables

Section 1: Hash Table


Introduction

Lesson 2: Creating Hash


Tables

Microsoft Confidential

457

Example:
Creating
hash
tables

Empty hash table


PS C:\> $hash = @{}

Create and populate hash table


PS C:\> $Server = `
@{ 'HV-SRV-1'='192.168.1.1' ; Memory=64GB ;
Serial='THX1138'}
PS C:\> $Server
Name

Value

----

-----

HV-SRV-1

192.168.1.1
458

Module 14: Hash Tables

Section 1: Hash Table


Introduction

Lesson 3: Accessing
Hash Table Items

Microsoft Confidential

461

Display all items in hash table


PS C:\> $Server

Example:
Access
hash
tables
items

Name
---HV-SRV-1
Serial
Memory

Value
----192.168.1.1
THX1138
68719476736

Return value using dot notation


PS C:\> $Server.'HV-SRV-1'
192.168.1.1
PS C:\> $Server.Serial
THX1138
Return value using index notation
PS C:\> $Server["Serial"]
THX1138
462

Example:
Display
all hash
tables
keys

Display all keys in hash table


PS C:\> $Server.Keys
HV-SRV-1
Serial
Memory

463

Example:
Display
all hash
tables
values

Display all values in hash table


PS C:\> $Server.Values
192.168.1.1
THX1138
68719476736

464

Module 14: Hash Tables

Section 1: Hash Table


Introduction

Lesson 4: Modifying
Hash Table Items

Microsoft Confidential

465

Add or set key and value using index notation


PS C:\> $Server["CPUCores"] = 4
Example:
Manipulat
e hash
table
items

Add or set key and value using dot notation


PS C:\> $Server.Drives="C", "D", "E"
Add key and value using hash table ADD method
PS C:\> $Server.Add("HotFixCount", `
(Get-HotFix Computer $Server[HV-SRV-1]).count)
Remove key
PS C:\> $Server.Remove("HotFixCount")

Module 14: Hash Tables

Section 1: Hash Table


Introduction

Lesson 5: Sorting Hash


Tables

Microsoft Confidential

467

Example:
Sorting
hash
tables

Hash tables are intrinsically unordered


It is not possible to sort a hash table
GetEnumerator() method used with Sort-Object Cmdlet
Sort hash table display by key
PS C:\> $Server.GetEnumerator() | Sort-Object -Property
key
Name
---CPUCores
Drives
HV-SRV-1
Memory
Serial

Value
----4
{C, D, E}
192.168.1.1
68719476736
THX1138
468

Module 14: Hash Tables

Section 1: Hash Table


Introduction

Lesson 6: Searching
Hash Tables

Microsoft Confidential

469

Example:
Searchin
g hash
tables

Searching a hash table


PS C:\> $hash = @{"John"=23342;"Linda"=54345;"James"=65467}
PS C:\> $hash.ContainsKey("Linda") # Fast hashed key search
True
PS C:\> $hash.ContainsValue(19)
False

# Slow non-hashed search

PS C:\> $hash.ContainsValue(65467)
True

470

Module 14: Hash Tables

Section 2: Hash Table Use


Cases

Lesson 1: Hash Table


Examples

Microsoft Confidential

471

Example
:
Calculat
ed
Property

Customizing property value on pipeline with Select-Object and a hash


table
Length property is in kilobytes and limited to 2 decimal points before
displayed

PS C:\> Get-ChildItem C:\Windows | Select-Object Name,


@{Name="Size (KB)";Expression={"{0:N2}" -f ($_.Length/1Kb)}}
Name
---HelpPane.exe
un_dext.exe
Key

Size (KB)
--------950.50
94.91

Valu
e

Valu
e

Key

@{Name="Size (KB)";Expression={"{0:N2}" -f ($_.Length/1Kb)}}


Hash
Table
472

Exampl
e:
Custom
PSObje
ct

Create a customized object (PS v2.0+) Ordering Not Preserved


$props = @{
Computer = (Get-WmiObject -Class Win32_computersystem).Name
Name = (Get-NetAdapter -Physical |
Where-Object {$_.status -eq up}).Name
Speed = (Get-NetAdapter -Physical |
Where-Object {$_.Status -eq up}).Linkspeed
}
$newobj = New-Object PSObject -Property $props

474

Exampl
e:
Custom
PSObje
ct

Create a customized object (PS v3.0+) Ordering Preserved


$newobj = [PSCustomObject]@{
Computer = (Get-WmiObject -Class Win32_computersystem).Name
Name = (Get-NetAdapter -Physical |
Where-Object {$_.status -eq up}).Name
Speed = (Get-NetAdapter -Physical |
Where-Object {$_.Status -eq up}).Linkspeed
}

475

Module 14: Hash Tables

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

PS C:\> @{firstname = "John" ; lastname = "Smith"}


Name
---lastname
firstname

Value
----Smith
John

Order not
preserved

PS C:\> [ordered]@{firstname = "John" ; lastname = "Smith"}


Name
---firstname
lastname

Value
----John
Smith

Microsoft Confidential

Insertion order
preserved

477

Module 14: Hash Tables

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

479

Module 15: Flow


Control

Module Overview

Microsoft Confidential

480

Module 15: Flow Control


Section 1: Looping
The Five Loops
While
Do While
Do Until
For
ForEach
Section 2: Branching
IF Statement
Basic SWITCH Statement
SWITCH Statement - Default Condition
SWITCH Statement - Multiple Inputs
SWITCH Statement - Case
SWITCH Statement - Wildcard
SWITCH Statement - Regex
SWITCH Statement - Expression Match

Microsoft Confidential

481

Module 15: Flow Control

Section 1: Looping

Lesson 1: The Five


Loops

Microsoft Confidential

482

PowerShells Five Loops


The loops in PowerShell repeat code
Five different logical variations:
Name

Loop Type Features

While

Conditional

Tests for $True condition

Do While Conditional

Tests for $True condition


Code block runs at least once

Do Until

Conditional

Tests for $False condition


Code block runs at least once

For

Conditional

Tests for $True condition


Includes Initialization and Repeat blocks

Foreach

Enumeratio
n

Runs code once for each item in


collection/array
Choose automatic variable name
Microsoft Confidential

483

Module 15: Flow Control

Section 1: Looping

Lesson 2: While

Microsoft Confidential

484

While Loop
Name Description

Example

While

$a = 0
While ($a lt 10) {$a; $a++}

Runs script block while


conditional test = true

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

Module 15: Flow Control

Section 1: Looping

Lesson 3: Do While

Microsoft Confidential

488

Do While Loop
Name Description
Do
While

Example

Condition evaluated AFTER script block $a = 0


runs at least once
Do {$a; $a++} While ($a -le 5)
Runs script block if conditional test =
true
Yes

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

Module 15: Flow Control

Section 1: Looping

Lesson 4: Do Until

Microsoft Confidential

491

Do Until Loop
Nam
e

Description

Example

Do
Until

Condition evaluated AFTER script


block runs at least once

Do {$a; $a++} Until ($a gt 10)

Runs script block if conditional test


= false
No

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

Module 15: Flow Control

Section 1: Looping

Lesson 5: For

Microsoft Confidential

494

For Loop
For

Runs script block while conditional test = true


Useful when targeting a subset of array values

Syntax

For (<init>; <condition>; <increment>)


{<statement list>}

Example

For ($a=1; $a lt 10; $a++) {$a}

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

Module 15: Flow Control

Section 1: Looping

Lesson 6: ForEach

Microsoft Confidential

498

ForEach Loop
ForEach

Good when targeting all array values

Syntax

ForEach ($<item> in $<collection>){<statement list>}

Example

ForEach ($file in Get-Childitem c:\windows -File) {$file.name}

Start

Items in
Array?

Yes

Set Value of $<item>


to current
array/collection
element

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

Module 15: Flow Control

Section 2: Branching

Lesson 1: IF Statement

Microsoft Confidential

502

IF Statement
Branching structure
chooses which code to
run

If

(<test1>) {<statement list 1>}

[ElseIf (<test2>) {<statement list 2>}]

Optional Elseif(s)
used for additional
test(s)

[ElseIf (<test3>) {<statement list 3>}]


[Else

{<statement list 4>}]

Optional Else code


runs if test(s) fail
Only one code block
will run
Microsoft Confidential

503

Option
al

If

Start

If (<test1>)
{
<statement list 1>
}

Is
condition
True?

Yes

Run Statement List


1

No
End

$Language = (Get-CimInstance -class win32_operatingsystem).OSLanguage


if ($Language -eq "1033")
{write-Host "Language = English US" -ForegroundColor Magenta}

Microsoft Confidential

504

If..Else
If (<test1>)
{
<statement list 1>
}
Else
{
<else statement list>
}

Start

Is
condition
True?

Yes

Run Statement List


1

No
Run Else Statement
List
End

$Language = (Get-CimInstance -class win32_operatingsystem).OSLanguage


if ($Language -eq "1033")
{write-Host "Language = English US" -ForegroundColor Magenta}
else
{Write-Host "Another Language" -ForegroundColor Cyan}
Microsoft Confidential

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

Run Statement List


1

Yes

Run Statement List


2

Yes

Run Statement List


3

No
Is second
condition
True?
No
No
Is third
condition
True?
No
End
Microsoft Confidential

506

Example:
If..ElseIf(s
)

$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
}

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

Run Statement List


1

No
Is second
condition
True?

Yes

Run Statement List


2

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

Module 15: Flow Control

Section 2: Branching

Lesson 2: Basic SWITCH


Statement

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

Module 15: Flow Control

Section 2: Branching

Lesson 3: SWITCH
Statement
- Default Condition

Microsoft Confidential

520

Switch With Default Case

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>

$DomainRole = (Get-CimInstance -class


Win32_ComputerSystem).DomainRole

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

Module 15: Flow Control

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

$FileNames = (Get-ChildItem C:\Windows).FullName


Switch -Wildcard ($FileNames)
{
"*.exe" {"Found executable: $_"}
Default {"Not an exe: $_"}
}

False
End
Microsoft Confidential

No
Conditions
Matched?

True

False

FalseAdditional

True

Values?

525

Run <action
2>

Example:
Switch with $_

$DomainRole = (Get-CimInstance -Class Win32_ComputerSystem).DomainRole


switch ($DomainRole)
{
1 {Write-Host "$_ : Member Workstation"}
2 {Write-Host "$_ : Standalone Server"}
}
PS C:\> 1 : Member Workstation

SWITCH works like pipeline


$_ or $PSItem can be used

526

Example:
SWITCH
Multiple
inputs

PS C:\> switch (123,200)


{
123 {Write-Host $_ -ForegroundColor Green}
200 {Write-Host $_ -ForegroundColor Cyan}
}
123
200

527

Module 15: Flow Control

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

switch -CaseSensitive ("HELLO")


{
"hello" {"lowercase"}
"HELLO" {"uppercase"}
}
uppercase

530

Module 15: Flow Control

Section 2: Branching

Lesson 6: SWITCH
Statement
Wildcard

Microsoft Confidential

531

Example:
SWITCH
without
-Wildcard

Switch (Get-ChildItem -Path c:\)


{
"program*" {Write-Host $_ -ForegroundColor Green}
"windows" {Write-Host $_ -ForegroundColor Cyan}
}
Wildcard characters not
matched

Windows

532

Example:
SWITCH with
-Wildcard

switch Wildcard (Get-ChildItem -Path c:\)


{
"program*" {Write-Host $_ -ForegroundColor Green}
"windows" {Write-Host $_ -ForegroundColor Cyan}
}
Program Files
Program Files (x86)
Windows
533

Module 15: Flow Control

Section 2: Branching

Lesson 7: SWITCH
Statement
Regex

Microsoft Confidential

534

Example:
SWITCH
with
-Regex

switch Regex (Get-ChildItem -Path c:\)


{
"^program" {Write-Host $_ -ForegroundColor Green}
"s$" {Write-Host $_ -ForegroundColor Cyan}
}
Program Files
Program Files
Program Files (x86)
Scripts
Users
Windows

^ Matches beginning character(s)


N $ Matches end character(s)
ot Get-Help
e about_Regular_Expressions
535

Module 15: Flow Control

Section 2: Branching

Lesson 8: SWITCH
Statement Expression
Match

Microsoft Confidential

536

Example:
SWITCH
Expression
matches

PS C:\> switch (123) {


{$_ -lt 124} {Write-Host $_ -ForegroundColor Green}
{$_ -gt 200} {Write-Host $_ -ForegroundColor Cyan}
}
123

537

Module 15: Flow Control

Section 2: Branching

Lesson 9: SWITCH
Statement File
Processing

Microsoft Confidential

538

Example:
SWITCH
-File

switch -File .\servers.txt


{
"server1" {Write-Host "$_ is in file" -ForegroundColor Green}
"server10" {Write-Host "$_ is in file" -ForegroundColor Cyan}
}
server1 is in file

539

Module 15: Flow Control

Section 2: Branching

Lesson 10: IF and


SWITCH Statement
Difference

Microsoft Confidential

540

IF and SWITCH Difference

IF statement terminates when a match is found

SWITCH statement does not terminate when a match is


found

SWITCH is more suitable when multiple conditions are


evaluated

Microsoft Confidential

541

Module 15: Flow


Control

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

547

Module 16: Scope

Module Overview

Microsoft Confidential

548

Module 16: Scopes


Section 1: Scope Introduction
What are Scopes?
Section 2: Scope Modifiers
Using Scope Modifiers

Section 3: Dot Source Notation


Dot Source Notation

Microsoft Confidential

549

Module 16: Scope

Section 1: Scope
Introduction

Lesson 1: What are


Scopes?

Microsoft Confidential

550

What are Scopes?


Created when launching scripts or functions
Separate items in memory (like variables)
Avoid naming collisions
Cleaned when script or function finishes

Microsoft Confidential

551

Scope determines lifetime & visibility of:


Variables
Functions
Aliases
PSDrives

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

Module 16: Scope

Section 2: Scope Modifiers

Lesson 1: Using Scope


Modifiers

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

Scope Modifiers - Variables


Variable Scope Modifier Syntax:
$[<scope-modifier>]:<name> = <value>

Example:
Change or create a variable in global scope from another
scope
$global:a = "one"

Microsoft Confidential

558

Scope Modifiers - Functions


Function Scope Modifier Syntax:
function [<scope-modifier>]:<name>
{<function-body>}
Example:
Make a function visible in global scope from another scope
function global:Hello
{write-host "Hello, World"}

Microsoft Confidential

559

Exampl
e:
List
items
in a
scope

List variables in local scope


PS C:\> Get-Variable -Scope Script

List PSDrives in local scope


PS C:\> Get-PSDrive -Scope Local

List aliases in global scope


PS C:\> Get-Alias -Scope Global

560

Module 16: Scope

Section 3: Dot Source


Notation

Lesson 1: Dot Source


Notation

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

Dot Source Script


PS C:\> . C:\Scripts\FunctionExample.ps1

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

Module 16: Scope

Section 4: Profiles

Lesson 1: Profiles

Microsoft Confidential

566

What are Profiles?


A start-up script that runs every time PowerShell starts
Any valid PowerShell script can be in profile
Profiles not exempt from execution policy
Four possible profile scripts for host

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

Profile 4 - Current User, Current Host


PS:/>

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

Profile Paths Common to ISE and Console


Scope
Current
User, All
Hosts
All Users,
All Hosts

Name
$Home\Documents\WindowsPowerShell\profile.ps1
$PsHome\profile.ps1

Microsoft Confidential

570

ISE Only Profile Paths


Scope
Current
User,
Current
Host
All Users,
Current
Host

Name
$Home\Documents\WindowsPowerShell\Microsoft.PowerShellISE_pr
ofile.ps1

$PsHome\Microsoft.PowerShellISE_profile.ps1

Note ISE in the filename

Microsoft Confidential

571

Console Only Profile Paths


Scope
Current
User,
Current
Host
All Users,
Current
Host

Name
$Home\Documents\WindowsPowerShell\Microsoft.PowerShell_profil
e.ps1

$PsHome\Microsoft.PowerShell_profile.ps1

Note no ISE in the


filename

Microsoft Confidential

572

Example:
Listing
Profile
Paths

PS C:\> $profile | Format-List -Property * -Force


AllUsersAllHosts
AllUsersCurrentHost

: 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

Script Libraries in Profiles


The profile script contents are automatically dotsourced
Scripts called from profile might need to be dotsourced
You can then access frequently used functions,
variables, aliases and PSDrives
Microsoft.PowerShell_profile.ps1
$now = Get-Date -Format 'dddd-hhmmtt'
Start-Transcript "C:\transcripts\PS-Transcript-$now.txt"
. \\2012R2-MS\ScriptLibrary\TeamProfile.ps1
Microsoft Confidential

574

Module 16: Scope

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

Module 10: Providers


Module 11: Variables & Data
Types
Module 12: Operators 2
Module 13: Arrays
Module 14: Hash Tables
Module 15: Flow Control
Module 16: Scope
Module 17: Modules

Microsoft Confidential

576

Module 17: Modules

Module Overview

Microsoft Confidential

577

Module 17: Modules


Section 1: Module Introduction
What are Modules?
Module Types
Cmdlets for Module Management
Module Loading

Section 2: Script Module


Creating a Script Module
Module Manifest

Microsoft Confidential

578

Module 17: Modules

Section 1: Module
Introduction

Lesson 1: What are


Modules?

Microsoft Confidential

579

What are Modules?


A package of commands
All cmdlets and providers in a session are added by a module or a
snap-in
Modules can contain cmdlets, scripts, functions, variables, aliases, and
other useful items
Modules are useful for sharing code

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

Module 17: Modules

Section 1: Module
Introduction

Lesson 2: Module Types

Microsoft Confidential

582

Module Types
Module Code
Binary
Module
(.dll)

Script
Module
(.psm1)

Typically
compiled cmdlets
and providers

Typically scripted
functions

Optional Module Manifest

Dynamic
Module
Exists only in
memory, created onthe-fly
Holds proxy functions
for implicit remoting

Module Manifests (.psd1) contain metadata


(version, HelpInfoUri, nested modules to load, etc.)
Microsoft Confidential

583

Module 17: Modules

Section 1: Module
Introduction

Lesson 3: Cmdlets for


Module Management

Microsoft Confidential

584

Get-Module Imported Modules

List imported modules


PS C:\> Get-Module
ModuleType
---------Script
Manifest
Manifest

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

Get-Module Available Modules


List installed modules available for loading
PS C:\> Get-Module -ListAvailable
Directory: C:\Users\administrator\Documents\WindowsPowerShell\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ---------------Script
0.0
ZIP {New-ZipFile, Get-ZipFile}
Directory: C:\Program Files\WindowsPowerShell\Modules
ModuleType Version Name
ExportedCommands
---------- ------- ------------------Script
0.0
TestModule {Say-Hello, Say-Goodbye}

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

Get-Module Remote Computer


Create a PowerShell remote session
PS C:\> $session = New-PSSession -ComputerName Server01

List modules installed on remote computer


PS C:\> Get-Module -PSSession $session -ListAvailable

Microsoft Confidential

587

Import-Module
Adds one or more modules to current session
Import module by name
PS C:\> Import-Module -Name BitsTransfer

Uses explicit path to import module


PS C:\> Import-Module -Name c:\ps-test\modules\test

Import module from remote computer (Implicit Remoting)


PS C:\> Import-Module ActiveDirectory -PSSession $session

Microsoft Confidential

588

Remove-Module
Removes one or more modules from current session
Does not delete/uninstall module from computer

Remove module by name


PS C:\> Remove-Module -Name BitsTransfer

Microsoft Confidential

589

Module 17: Modules

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

List module path folders


PS C:\> $env:PSModulePath -split ';'
C:\Users\John\Documents\WindowsPowerShell\Modules
C:\windows\system32\WindowsPowerShell\v1.0\Modules
C:\Program Files\WindowsPowerShell\Modules

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

Get name of snap-in or module from which a cmdlet originates

Example:
GetCommand
Support
for
Modules

PS C:\> (Get-Command Get-Date).ModuleName


Microsoft.PowerShell.Utility
Get commands in PSScheduledJob module
PS C:\> Get-Command -Module PSScheduledJob
CommandType Name
----------- ---Cmdlet
Add-JobTrigger
...

ModuleName
---------PSScheduledJob

Get only commands in current session


PS C:\> Get-Command -ListImported
CommandType

Name ModuleName

-----------

---- ----------

Function
...

A:
594

Module 17: Modules

Section 2: Script Module

Lesson 1: Creating a
Script Module

Microsoft Confidential

595

Creating a Script Module


A script module can be as simple as a small script with a .psm1
extension
Typically contain function definitions
The script runs upon module import
By default, functions and variables remain
available
use in
Import
Script asfor
Module
PowerShell session
Create Module Script
1. Import-Module c:\MyModule.psm1
MyModule.psm1
Function Get-Data
{
Simple function
}

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

Module 17: Modules

Section 2: Script Module

Lesson 2: Module
Manifest

Microsoft Confidential

598

Module Manifests Enhance Script Modules


Created via New-ModuleManifest cmdlet as a separate .psd1 file
Manifest is a simple hash table containing metadata
Becomes a manifest module
MyModule.psd1

MyModule

# Module manifest for module


'testmanifest'
# Generated by: Joe Public
# Generated on: 10/17/2012
@{
MyModule.psm1
# Script module or binary module file
MyModule.psd1
RootModule = 'MyModule.psm1'
# Version number of this module.
ModuleVersion = '1.2'
Folder in PSModulePath
# ID used to uniquely identify this module
GUID = '6995bbea-221d-4b87-8234le
b
a
t
bcdd9323c82d'
sh
a
H
...
Microsoft
Confidential
599

Module 17: Modules

Section 3: Module Scope

Lesson 1: Module Scope

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

Module 17: Modules

Lab

Microsoft Confidential

602

Appendix: PowerShell Best


Practices

Microsoft Confidential

603

Windows PowerShell best practices


Scripts

Write your code for someone else to read


Comment your code where warranted
Add help documentation to your script or function, with examples
Use native PowerShell, rather than equivalent external commands
one function implements one task (Verb-Noun)
Expand all aliases
Let the ISE expand the Cmdlet (using <TAB>) for spelling and correct case
Use code-signing for production scripts
Invoke-expression can be used for code-injection, so use carefully
Declare all variables in scope before use
Use the Module concept to group related functions into a single suite

Pipeline

Filter to the left, format to the right


Accept input from the pipeline and send output to the pipeline

Microsoft Confidential

Windows PowerShell best practices continued


Functions

Use named parameters (avoid positional parameters)


Include [CmdletBinding()] to enable common parameters. Requires a Param()
statement
Use Write-Verbose, Write-Error and Write-Debug cmdlets to leverage Cmdlet
binding
Use [OutputType()] in your functions(enables intellisense)
If a parameter refers to a file path, name the parameter PATH or use an alias of
PATH
Name your parameters using the existing cmdlet naming conventions.
Assign default values to function parameters
Specify validation attributes for function parameters
Use Out-* and Write-* cmdlets properly. Write-host only emits to the host
application
Make use of switch parameters to enact different behaviours
Implement WhatIf for dangerous choices

Click
to add
Clickicon
icon
to picture

add picture

Windows PowerShell v4.0


for the IT Professional
Part 1
THANK YOU

Click icon to

Microsoft Confidential

607

Das könnte Ihnen auch gefallen