You are on page 1of 571

Windows PowerShell v4.

0 for the IT
Professional
Part 1

Luís Henrique Demetrio


Senior Premier Field Engineer
luis.demetrio@microsoft.com

Twitter: @demetrio_casao
MSDN: https://aka.ms/luisdem
Luís Henrique Demetrio

http://aka.ms/luisdem
luis.demetrio@microsoft.com
@demetrio_casao
Introductions About You:

• Name

• Company Affiliation

• Title/Function/Area of Responsibility

• Product experience

• Expectations for this Course

Microsoft Confidential Microsoft Confidential 4


Workshop Schedule Start: 9:00 am

Break: 10:30 am

Lunch: 12:30 pm

Break: 2:45 pm

End: 5:00 pm

Microsoft Confidential Microsoft Confidential 5


Agenda
Module 1: Introduction Module 9: Pipeline 2
Module 2: Commands 1 Module 10: Providers
DAY 1

DAY 3
Module 3: Pipeline 1 Module 11: Variables & Data Types
Module 4: Commands 2 Module 12: Operators 2
Module 5: Scripts Module 13: Arrays
Module 6: Help System Module 14: Hash Tables
DAY 2

Module 7: Object Models Module 15: Flow Control

DAY 4
Module 8: Operators 1 Module 16: Scope
Module 17: Modules

Microsoft Confidential
2012R2-DC 2012R2-MS WIN8-WS

Lab Windows Server 2012 R2 Windows Server 2012 R2 Windows 8.1

Environment Core

Domain Controller Domain Member Domain Member


Server Workstation

10.0.1.200 10.0.1.210 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 non-infringement.
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 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 9
Module 1: Introduction

Module Overview

Microsoft Confidential 10
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 11
Module 1: Introduction

Section 1: Shell Lesson 1: What is PowerShell?

Microsoft Confidential 12
What is a Shell?
Reusable
Software enabling OS Utilities

and Application access


Shells
through interactive commands
or batches of commands (scripts)
Applications

Kernel

Hardware

Microsoft Confidential 13
What is PowerShell?

• Automation Engine • Development Framework:


• Command-line Shell o Integrated Scripting Environment
• Scripting Language o PowerShell Embedded in Host Applications

Microsoft Confidential 15
PowerShell Evolution

3.0 4.0
Code Name: 1.0 2.0
Monad
2005 2006 2008 2012 2013

130 cmdlets 230 cmdlets >2,300 >2,300


Backward- cmdlets cmdlets
Compatible Backward- Backward-
Integrated Compatible Compatible
Shell WinPE Desired State
Environment Web Access Configuration
(ISE) (DSC)
Enhanced ISE
Remoting
Workflow

Microsoft Confidential 16
PowerShell default availability

Windows PowerShell is a Windows feature

• Windows 8.1
Windows PowerShell 4.0 • Windows Server 2012R2

• Windows 8
Windows PowerShell 3.0 • Windows Server 2012

• Windows 7
Windows PowerShell 2.0 • Windows Server 2008 R2

Windows PowerShell 1.0 • Windows Server 2008

Microsoft Confidential Microsoft Confidential 17


Installing PowerShell versions
No 1.0 1.0 as Update 2.0 2.0 as 3.0 3.0 as 4.0 4.0 as
PowerShell Update Update Update
(WMF) (WMF) (WMF)
XP
2003
Vista
2008
2008R2
Win7
Win8
2012
Win8.1
2012R2

WMF: Windows Management Framework


Grouping of several management related tools such as PowerShell, BITS, and the WinRM service
Microsoft Confidential 18
System Requirements

.Net • .Net Framework


Framework v4.5

• Windows 7 SP1
• Windows Server
2008 R2 SP1
OS
• Windows 8.1
• Windows Server
4.0 2012 or 2012 R2

• WMI, WinRM and


Server Manager
Other CIM Provider
(Included in
Windows or WMF)

Microsoft Confidential 19
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 20
Module 1: Introduction

Section 2: PowerShell Features Lesson 1: PowerShell Hosts

Microsoft Confidential 21
Command-Line Interface (CLI)
• Interactive mode
• Simple commands to interact with applications and the operating system
• Handy shortcut keys: HOME, END, arrows, CTRL+arrows

Microsoft Confidential 22
Integrated Scripting Environment (ISE)

• Development Tool
• Graphical Editor
• Execution and Debugging

Windows 8 / Server 2012


Start Screen Tile

Taskbar Tile
Microsoft Confidential 23
Module 1: Introduction

Section 2: PowerShell Features Lesson 2: Scripting Language

Microsoft Confidential 24
Scripting Language
Interactive Commands batched together:

• Automation • Health Check


• Disaster Recovery • Monitoring
• High Availability • Reporting
• Deployment • GUI over PowerShell
• Auditing • ...

Microsoft Confidential 25
Module 1: Introduction

Section 2: PowerShell Features Lesson 3: Interactive Scripting


Environment (ISE)

Microsoft Confidential 26
Anatomy of the ISE

PowerShell
tabs

Script
Scripts pane
open within
a tab Show-
Command
add-on

Console
pane

Microsoft Confidential 27
Module 1: Introduction

Section 2: PowerShell Features Lesson 4: Extended Features

Microsoft Confidential 28
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 30


PSWA Browser Experience

Microsoft Confidential 33
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 35


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 41


Module 1: Introduction

End of Module

Microsoft Confidential 48
Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 49
Module 2: Commands 1

Module Overview

Microsoft Confidential 50
Module 2: Commands 1
Section 1: Command Introduction Section 3: Cmdlet Alternate Names
• External Commands • Built-in Aliases
• Cmdlet Syntax • User-defined Aliases
• Cmdlet Common Parameters
• Command Termination and Line
Continuation

Section 2: Core Cmdlets


• Get-Command and Show-
Command
• Get-Help

Microsoft Confidential 51
Module 2: Commands 1

Section 1: Command Introduction Lesson 1: External Commands

Microsoft Confidential 52
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 53
Module 2: Commands 1

Section 1: Command Introduction Lesson 2: Cmdlets

Microsoft Confidential 54
What is a Cmdlet?

Verb-Noun
Single purpose
naming

Does not launch Used interactively,


in a separate in pipelines, or in
process scripts

Native PowerShell
Cmdlet Parameters to
control Cmdlet
command behaviour

Microsoft Confidential 55
Anatomy of a Cmdlet

Command Command
Name Parameters

Stop-Service -Name Spooler -Force

Parameter Parameter Switch


Verb Noun
Name Value Parameter

Microsoft Confidential 56
Cmdlet Examples
PS C:\> Get-Process

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


------- ------ ----- ----- ----- ------ -- -----------
83 7 1084 4124 45 0.09 7784 armsvc
179 13 1892 8216 89 0.66 6540 BDAppHost
143 12 1840 7320 76 0.22 11148 BDExtHost
...

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

VERBOSE: Performing the operation "Restart-Service" on target "Print


Spooler (Spooler)".

PS C:\> Test-Connection -ComputerName 2012R2-MS -Count 1 –Quiet


True
Microsoft Confidential 57
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 58
Syntax Legend

<verb-noun> Command name

-<parameter> Required parameter name

<value> Required parameter value

[-<> <>] Optional parameter and/or value

<value[ ]> Multiple parameter values

Microsoft Confidential 59
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 60
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 61
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 62
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 63
Cmdlet Syntax - Optional Parameter, Required 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 64
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 65
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 66
Module 2: Commands 1

Section 1: Command Introduction Lesson 3: Cmdlet Common


Parameters

Microsoft Confidential 67
Common Parameters

• Parameters automatically available with any Cmdlet

• Implemented by PowerShell not Cmdlet developer

• Override system defaults or preferences

Microsoft Confidential 68
Common Parameters (with alias in parenthesis)
-Debug (db) Displays programmer-level detail
-ErrorAction (ea) Determines how cmdlet responds to errors
-ErrorVariable (ev) Stores error messages in a specified variable
-OutVariable (ov) Stores output in a specified variable
-OutBuffer (ob) Determines number of output objects to accumulate in a
buffer
-PipelineVariable (pv) Stores value of current pipeline* element as a variable
-Verbose (vb) Displays detailed information
-WarningAction (wa) Determines how cmdlet responds to warnings
-WarningVariable (wv) Stores warnings in a specified variable
* Pipeline is discussed in module 3
Microsoft Confidential 69
Example: PS C:\> Restart-Service –Name Netlogon
Common PS C:\>
Parameters
in Use -
Verbose Common
Parameter

PS C:\> Restart-Service –Name Netlogon –Verbose


VERBOSE: Performing the operation "Restart-Service" on target
"Netlogon (Netlogon)".

PS C:\>

Microsoft Confidential 70
Example: PS C:\> Get-Process Netlogon
Common
Parameters Get-Process : Cannot find a process with the name "Netlogon".
in Use - Verify the process name and call the cmdlet again.
ErrorAction 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 Error Action


Microsoft Confidential 71
Example: PS C:\> Get-FileHash .\iExploreProcesses.csv -OutVariable csvhash
Store
command
output in a
specified Common Variable
variable name Parameter Name

Use the variable to retrieve the command output


PS C:\> $csvhash

Algorithm Hash Path


----------- ---- ----
SHA256 6A78… C:\iExploreProcesses.csv
Note: $ prefix denotes a variable in PowerShell

Microsoft Confidential 72
Risk Mitigation Parameters

• Many cmdlets also offer risk mitigation parameters


• Typically when the cmdlet changes the system or application

-WhatIf (wi) Displays message describing the effect of the command, instead of
executing the command
-Confirm (cf) Prompts for confirmation before executing command

Microsoft Confidential 73
Example: PS C:\> Stop-Process -Name * -WhatIf
-WhatIf
What if: Performing the operation "Stop-Process" on target "AcroRd32 (8160)".
Parameter in What if: Performing the operation "Stop-Process" on target "AcroRd32 (12756)".
use What if: Performing the operation "Stop-Process" on target "armsvc (2468)".
What if: Performing the operation "Stop-Process" on target "atieclxx (3220)".
What if: Performing the operation "Stop-Process" on target "atiesrxx (780)".
What if: Performing the operation "Stop-Process" on target "audiodg (9576)".
...

Microsoft Confidential 74
Module 2: Commands 1

Section 1: Command Introduction Lesson 4: Command Termination


and Line Continuation

Microsoft Confidential 75
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 76


Example: Semi-colon command termination
Use PS C:\> Get-Service BITS ; Get-Process System
command
termination
Status Name DisplayName
character
------ ---- -----------
Running BITS Background Intelligent Transfer Ser...

Id : 4
Handles : 1308
CPU : 1213.59375
Name : System

Microsoft Confidential 77
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 78


Example: PS C:\> "This is a multi-line
Line >> string that continues
Continuation >> 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 79
Module 2: Commands 1

Section 2: Core Cmdlets Lesson 1: Get-Command and


Show-Command

Microsoft Confidential 80
Get-Command

• Discover Commands (cmdlets, functions, scripts, aliases)

• Can show command syntax

• Can also discover external commands (.exe, .cpl, .msc)

Microsoft Confidential 81
PS C:\> Get-Command
Example:
Get- CommandType Name Definition
Command ----------- ---- ----------
Cmdlet Add-Content 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 82
PS C:\> Get-Command -Name *user*
Example:
Wildcard CommandType Name
in Name ----------- ----
Function UpdateDefaultPreferencesWi...
Cmdlet Get-WinUserLanguageList
Cmdlet New-WinUserLanguageList
Cmdlet Set-WinUserLanguageList
Cmdlet Test-UserGroupMembership
Application DsmUserTask.exe
Application quser.exe
Application UserAccountBroker.exe
Application UserAccountControlSettings...
Application userinit.exe

Microsoft Confidential 83
PS C:\> Get-Command -Verb Get
Example:
List Cmdlets CommandType Name ModuleName
By Verb ----------- ---- ----------
Alias Get-GPPermissions GroupPolicy
Alias Get-ProvisionedAppxPackage Dism
Function Get-AppBackgroundTask AppBackgroundTask
...

Microsoft Confidential 84
PS C:\> Get-Command -Noun Service
Example:
List CommandType Name ModuleName
Cmdlets ----------- ---- ----------
By Noun Cmdlet Get-Service Microsoft.PowerShell.Management
Cmdlet New-Service Microsoft.PowerShell.Management
Cmdlet Restart-Service Microsoft.PowerShell.Management
Cmdlet Resume-Service Microsoft.PowerShell.Management
...

Microsoft Confidential 85
PS C:\> Get-Command -CommandType Cmdlet
Example:
List CommandType Name ModuleName
Cmdlets ----------- ---- ----------
Only Cmdlet Add-ADCentralAccessPolicyMember ActiveDirectory
Cmdlet Add-ADComputerServiceAccount ActiveDirectory
...

Microsoft Confidential 86
PS C:\> Get-Command -Name dir
Example:
Single
Command CommandType Name ModuleName
----------- ---- ----------
Alias dir -> Get-ChildItem

Microsoft Confidential 87
PS C:\> Get-Command Get-WinEvent -Syntax
Example:
List Cmdlet Get-WinEvent [[-LogName] <string[]>] [-MaxEvents <long>]
syntax with [-ComputerName <string>] [-Credential <pscredential>]
Get- [-FilterXPath <string>] [-Force] [-Oldest] [<CommonParameters>]
Command
Get-WinEvent [-ListLog] <string[]> [-ComputerName <string>]
[-Credential <pscredential>] [-Force] [<CommonParameters>]

Get-WinEvent [-ListProvider] <string[]> [-ComputerName <string>]


[-Credential <pscredential>] [<CommonParameters>]

...

Microsoft Confidential 88
Show-Command
• Show-Command cmdlet launches GUI
Command Browser Fill in
• Populate Parameters and Insert or Execute Parameters

Execute
Command
PS C:\> Show-Command
Directly

Insert
Command
Start Typing with
Command Parameters
Name Populated
and/or click
on command
PS C:\> Get-Process -ComputerName 2012DC
in list -Name system -ErrorAction SilentlyContinue

Microsoft Confidential 89
Module 2: Commands 1

Section 2: Core Cmdlets Lesson 2: Get-Help

Microsoft Confidential 90
Get-Help

• Cmdlet help
• Concept Help
• Command Examples
• Detailed Syntax

Microsoft Confidential 91
PS C:\> Get-Help Get-ChildItem
Example:
#or
Help for PS C:\> Get-ChildItem -?
Cmdlets –
Default NAME
Get-ChildItem
Short View 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 92
Example: PS C:\> Get-Help Get-ChildItem
PS C:\> Get-Help Get-ChildItem –Full
Help for
PS C:\> Get-Help Get-ChildItem –Examples
Cmdlets – PS C:\> Get-Help Get-ChildItem –Detailed
Full View
Default Help Sections (no params) All Help Sections (-Full)
NAME NAME
SYNOPSIS SYNOPSIS
SYNTAX SYNTAX
DESCRIPTION DESCRIPTION
RELATED LINKS PARAMETERS
REMARKS INPUTS
OUTPUTS
NOTES
EXAMPLES
RELATED LINKS
Microsoft Confidential 93
Example: PS C:\> Get-Help Get-Counter -Parameter Counter
Help for
-Counter <String[]>
Specified Gets data from the specified performance counters. Enter one
Cmdlet or more
Parameter(s) ...

Each counter path has the following format:

"[\\<ComputerName>]\<CounterSet>(<Instance>)\<CounterName>"

...
Required? false
Position? 1
Default value
Accept pipeline input? true (ByValue, ByPropertyName)
Accept wildcard characters? True
Microsoft Confidential 94
Module 2: Commands 1

Section 3: Cmdlet Alternate Lesson 1: Aliases


Names

Microsoft Confidential 95
PS C:\> Get-Alias
Example:
Listing all aliases CommandType Name ModuleName
----------- ---- ----------
Alias % -> ForEach-Object
Alias ? -> Where-Object
Alias ac -> Add-Content
Alias asnp -> Add-PSSnapin
Alias cat -> Get-Content
Alias cd -> Set-Location
Alias chdir -> Set-Location
...

Microsoft Confidential 96
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 97
Example: Full cmdlet name
Using built-in aliases 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 98
Module 2: Commands 1

Section 3: Cmdlet Alternate Lesson 2: User-defined Aliases


Names

Microsoft Confidential 99
Example: New Alias (list) for Get-ChildItem cmdlet
Creating a PS C:\> New-Alias -Name list -Value Get-ChildItem
custom alias
Using New Alias (list)
PS C:\> list

Directory: C:\

Mode LastWriteTime Length Name


---- ------------- ------ ----
d---- 5/09/2013 1:40 PM Intel
d-r-- 21/10/2013 1:31 PM Program Files
d-r-- 10/12/2013 10:26 AM Program Files (x86)
d---- 1/12/2013 1:32 PM Scripts

Microsoft Confidential 100


Module 2: Commands 1

Lab

Microsoft Confidential 101


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 102


Module 3: Pipeline 1

Module Overview

Microsoft Confidential 103


Module 3: Pipeline 1
Section 1: Pipeline Introduction
• What is a pipeline? Section 4: Pipeline Output
• Format Cmdlets
Section 2: Pipeline Input • Export Cmdlets
• Get cmdlets, Text file and External • Out Cmdlets
Command

Section 3: Pipeline Object Manipulation


• Object Cmdlets

Microsoft Confidential 104


Module 3: Pipeline 1

Section 1: Pipeline Introduction Lesson 1: What is a pipeline?

Microsoft Confidential 105


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 106


Module 3: Pipeline 1

Section 2: Pipeline Input Lesson 1: “Get” Cmdlets


External Commands
Text File input

Microsoft Confidential 107


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 108


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


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

Import-Csv Import-CliXml

• Key Parameters: • Key Parameters:


• -Path • -Path
• -Delimiter • -First
• -Header

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

Microsoft Confidential 111


Module 3: Pipeline 1

Section 3: Pipeline Object Lesson 1: Object Cmdlets


Manipulation

Microsoft Confidential 112


Object Cmdlets

Name Description
Sort-Object Sorts objects by property values
Select-Object Selects object properties
Group-Object Groups objects that contain the same value for specified properties
Measure-Object Calculates numeric properties of objects, and the characters, words,
and lines in string objects, such as text files
Compare-Object Compares two sets of objects

Microsoft Confidential 113


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 NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName


------- ------ ----- ----- ----- ------ -- -----------
1283 55 21020 30340 1237 477.78 304 svchost
1926 44 285244 230112 1165 716.45 4124 livecomm

Microsoft Confidential 114


Example:
Group-Object

Get security event log then Group by entry type


PS C:\> Get-EventLog -LogName Security |
Group-Object EntryType

Count Name Group


----- ---- -----
18105 SuccessAudit {System.Diagnostics.EventLogEntry,Sys...
25 FailureAudit {System.Diagnostics.EventLogEntry,Sys...

Microsoft Confidential 115


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 : 2
Average :
Sum : 217837
Maximum :
Minimum :
Property : Length
Microsoft Confidential 116
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 117
Module 3: Pipeline 1

Section 4: Pipeline Output Lesson 1: Format Cmdlets

Microsoft Confidential 118


Format Cmdlets
• Convert pipeline objects into formatted output, typically for human consumption
• Should be last Cmdlet on the pipeline (only followed by Out-* Cmdlets)

Format-List Format-Table Format-Wide


• “-Property *” • Parameters: • Key Parameters:
• lists all properties • -Autosize • -Autosize
available • -Wrap • -Column

Microsoft Confidential 119


Example: PS C:\> Get-Process -Name powershell | Format-List
Format-List with
Default Id : 6400
Handles : 472
Properties
CPU : 0.78125
Name : powershell

• Output is in list format


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

Microsoft Confidential 120


Example: PS C:\> Get-Process -Name powershell |
Format-List with Format-List -Property Name, BasePriority, PriorityClass
specific
Name : powershell
properties
BasePriority : 8
PriorityClass : Normal

• Output in list format


• Consists of specified properties

Microsoft Confidential 121


PS C:\> Get-Process | Format-Table
Example:
Format-Table Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
with default ------- ------ ----- ----- ----- ------ -- -----------
82 7 1308 1420 45 0.14 2308 armsvc
properties 195 13 2568 3440 94 3.78 1192 atieclxx
110 6 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 122


PS C:\> Get-Process |
Example: Format-Table –Property name,workingset,handles
Format-Table
with specific Name WorkingSet Handles
properties ---- ---------- -------
csrss 847872 216
csrss 356352 91
csrss 15646720 183
dwm 7045120 176
dwm 30498816 201
explorer 37539840 1427
Idle 4096 0
LogonUI 6897664 367
lsass 7622656 1050
MsMpEng 24444928 528
powershell_ise 144850944 515
...

Microsoft Confidential 123


PS C:\> Get-Process |
Example: Format-Table -Property name,workingset,handles -AutoSize
Format-Table
with specific Name WorkingSet Handles
properties and - ---- ---------- -------
AutoSize 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 124


PS C:\> Get-Process | Format-Table -Property Name,Path,WorkingSet
Example:
Format-Table Name Path WorkingSet
with specific ---- ---- ----------
properties armsvc 1454080
atieclxx 3760128
atiesrxx 1200128
audiodg 11911168
BDAppHost C:\Program Fil... 2736128
BDExtHost C:\Program Fil... 1826816
BDRuntimeHost C:\Program Fil... 15331328
BingDesktop C:\Program Fil... 10981376
CCC C:\Program Fil... 5857280
...

Path truncated due to wide


values
Microsoft Confidential 125
PS C:\> Get-Process | Format-Table -Property Name,Path,WorkingSet -AutoSize
Example:
Format-Table Name Path
with Auto Sized ---- ----
armsvc
Columns atieclxx
atiesrxx
BDAppHost C:\Program Files (x86)\Microsoft\BingDesktop\BDAppHost.exe
BDExtHost C:\Program Files (x86)\Microsoft\BingDesktop\BDExtHost.exe
BDRuntimeHost C:\Program Files (x86)\Microsoft\BingDesktop\BDRuntimeHost...
BingDesktop C:\Program Files (x86)\Microsoft\BingDesktop\BingDesktop.exe
CCC C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Stati...
...

Path property truncation is


minimized with –Autosize,
but workingset column lost

Microsoft Confidential 126


PS C:\> Get-Process |
Format-Table -Property Name,Path,WorkingSet -AutoSize –Wrap
Example:
Format-Table Path property is line
Name Path wrapped, workingset still
with Wrap ---- ---- lost in this case
armsvc
atieclxx
atiesrxx
BDAppHost 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 127


PS C:\> Get-Process |
Sort-Object -Property BasePriority |
Example: Format-Table -GroupBy BasePriority -Wrap -AutoSize
Format-Table
with Grouping BasePriority: 0 Processes are grouped by 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 Group


----- ---- -----
181027 SuccessAudit {System.Diagnostics.EventLogEntry}
25 FailureAudit {System.Diagnostics.EventLogEntry}
Autosize minimizes data
truncation, wrap eliminates it Microsoft Confidential 128
PS C:\> Get-ChildItem | Format-Wide
Example:
Format-Wide – Directory: C:\
Default 2
Columns [PerfLogs] [Program Files]
[Program Files (x86)] [PShell]
[Users] [Windows]
[WPLUS_EULA]

Output displayed in 2
columns by default

Microsoft Confidential 129


PS C:\> Get-ChildItem | Format-Wide -Column 3
Example:
Format-Wide – Directory: C:\
Explicit number
of Columns [Intel] [PerfLogs] [Program Files]
[Program Files (x86)] [Users] [Windows]

Output displayed in 3
columns

Microsoft Confidential 130


PS C:\> Get-Alias | Format-Wide -AutoSize
Example:
Format-Wide –
AutoSize % ? ac asnp cat cd chdir
maximizes clc clear clhy cli clp cls clv
columns cnsn compare copy cp cpi cpp curl
cvpa dbp del diff dir dnsn ebp
echo epal epcsv epsn erase etsn exsn
fc fl foreach ft fw gal gbp
gc gci gcm gcs gdr ghy gi
gjb gl gm gmo gp gps group

Output displayed in max


numbers of columns based
on widest data

Microsoft Confidential 131


Module 3: Pipeline 1

Section 4: Pipeline Output Lesson 2: Export and Import


Cmdlets

Microsoft Confidential 132


Export Cmdlets
• Export pipeline objects to text file

• Should be last cmdlet on the pipeline

Export-Csv Export-CliXml

• Key Properties: • Key Properties


• -Path • -Path
• -Delimiter • -Depth

Microsoft Confidential 133


Example:
Export- PS C:\> get-acl C:\Process.txt -Audit |
Clixml Export-Clixml -Path fileacl.xml

PS C:\> notepad .\fileacl.xml

Microsoft Confidential 134


Example:
Export-CSV 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 135


PS C:\> Import-Csv C:\usermailbox.csv | Select-Object mailbox
Example:
Import-Csv Mailbox
-------
administrator@contoso.com
dpark@contoso.com
kakers@contoso.com

Microsoft Confidential 136


Module 3: Pipeline 1

Section 4: Pipeline Output Lesson 3: Out Cmdlets

Microsoft Confidential 137


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
Out-GridView 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 138
PS C:\> Get-Process | Out-GridView
Example:
Out-Gridview

Microsoft Confidential 139


Step 1: Send Get-Process output to Out-Gridview with PassThru switch
parameter, followed by export to CSV
PS C:\> Get-Process | Out-GridView -PassThru |
Example: Export-Csv c:\scripts\iExploreProcesses.csv -NoTypeInformation
Out-Gridview
with PassThru

Step 2: Filter using GUI.


Click to select output items Step 3: View filtered output in CSV

Microsoft Confidential 140


Module 3: Pipeline 1

Section 4: Pipeline Output Lesson 4: Storing output in a


Variable

Microsoft Confidential 142


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


----- ---- -----
135950 SuccessAudit {System.Diagnostics.EventLogEntry...
40 FailureAudit {System.Diagnostics.EventLogEntry...

Microsoft Confidential 143


Module 3: Pipeline 1

Lab

Microsoft Confidential 144


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 145


Module 4: Commands 2

Module Overview

Microsoft Confidential 146


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 147


Module 4: Commands 2

Section 1: Script Blocks Lesson 1: What is a Script Block?

Microsoft Confidential 148


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 149
PS C:\> Invoke-Command -ScriptBlock {Get-Process} –ComputerName
Example:
>> 2012R2-DC, 2012R2-MS, WIN8-WS
Cmdlet with
ScriptBlock Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
parameter ------- ------ ----- ----- ----- ------ -- -----------
argument 4848 55 48316 64252 237 3,077.20 1840 CcmExec
76 8 1948 7180 60 3.55 9356 conhost
386 23 7768 18512 286 0.16 14092 csrss
...
PS C:\> Measure-Command -Expression {Get-Process}

Days : 0
Minutes : 0
Seconds : 2
Milliseconds : 933
Ticks : 29332816
...
Microsoft Confidential 150
Module 4: Commands 2

Section 2: Functions Lesson 1: Functions Introduction

Microsoft Confidential 151


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 152


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 153


Example: • A series of commands can be contained in a function
Creating a
utility function PS C:\> Get-Service -Name spooler -RequiredServices
-ComputerName 2012R2DC

• Run the function

PS C:\> Get-ServiceInfo

Microsoft Confidential 154


Example: • A series of commands can be contained in a function
Creating a
utility function • Cmdlet parameter values become function parameters
with
parameters

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

Microsoft Confidential 155


Module 4: Commands 2

Section 3: Remoting Lesson 1: Introduction to


PowerShell Remoting

Microsoft Confidential 156


Entry Point Transport Network
Resource-Specific
Cmdlets
Various Native OS Remoting
RPC
PowerShell WMI Cmdlets DCOM
Remote
Administration
Techniques CIM Cmdlets

TCP/IP

Microsoft Confidential
Entry Point Transport Network
Resource-Specific
Cmdlets
Various Native OS Remoting
RPC
PowerShell WMI Cmdlets DCOM
Remote
Administration
Techniques CIM Cmdlets

CIM Sessions TCP/IP


CDXML Cmdlets Connection Settings
Only, Non-Stateful
WS-MAN
DSC Cmdlets

Microsoft Confidential
Entry Point Transport Network
Resource-Specific
Cmdlets
Various Native OS Remoting
RPC
PowerShell WMI Cmdlets DCOM
Remote
Administration
Techniques CIM Cmdlets

CIM Sessions TCP/IP


CDXML Cmdlets Connection Settings
Only, Non-Stateful
Featured in WS-MAN
this Module DSC Cmdlets

Workflows PSSessions
Stateful Connection
Remoting Cmdlets
Microsoft Confidential
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 160


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) PS C:\>

Microsoft Confidential 161


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 OS’s

Remote User Permissions:


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

Microsoft Confidential 162


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 163


Module 4: Commands 2

Section 3: Remoting Lesson 2: Using PowerShell


Remoting

Microsoft Confidential 164


PS C:\> Enter-PSSession -ComputerName 2012R2-DC
Example:
Interactive Remote
Computer
Session
[2012R2-DC] PS C:\>

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


2012R2-DC session

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

Local Computer
PS C:\>

166
PS C:\> Invoke-Command -ComputerName 2012R2-DC
Example:
>> -ScriptBlock {Get-Culture}
Invoke a
command LCID Name DisplayName PSComputerName
---- ---- ----------- --------------
3081 en-AU English (Australia) 2012R2-DC

167
PS C:\> Invoke-Command -ComputerName 2012R2-DC, 2012R2-MS
Example:
>> -ScriptBlock {Get-Culture}
Invoke a
command LCID Name DisplayName PSComputerName
(1:many) ---- ---- ----------- --------------
1033 en-US English (United States) 2012R2-MS
1033 en-US English (United States) 2012R2-DC

168
PS C:\> Invoke-Command -ComputerName 2012R2-DC –Credential
Example:
>> contoso\administrator -ScriptBlock {Get-Culture}
Use alternate
credential LCID Name DisplayName PSComputerName
---- ---- ----------- --------------
3081 en-AU English (Australia) 2012R2-DC

169
Example: Step 1: Create a persistent session
Persistent PS C:\> New-PSSession -ComputerName 2012R2-DC –OutVariable ps
Session
Id Name ComputerName State ConfigurationName Availability
(repeat -- ---- ------------ ----- ----------------- ------------
use) 1 Session1 2012R2-DC Opened Microsoft.PowerShell Available

Step 2: Use the session


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

LCID Name DisplayName PSComputerName


---- ---- ----------- --------------
3081 en-AU English (Australia) 2012R2-DC

170
Example: Step 1: Create persistent sessions
Persistent PS C:\> New-PSSession -ComputerName 2012R2-DC, 2012R2-MS
Session –OutVariable ps
(repeat Id Name ComputerName State ConfigurationName Availability
use) -- ---- ------------ ----- ----------------- ------------
1:many 1 Session1 2012R2-DC Opened Microsoft.PowerShell Available
2 Session2 2012R2-MS Opened Microsoft.PowerShell 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
1033 en-US English (United States) 2012R2-MS
171
Module 4: Commands 2

Lab

Microsoft Confidential 172


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 173


Module 5: Scripts

Module Overview

Microsoft Confidential 174


Module 5: Scripts
Section 1: Introduction to Scripts Section 4: Script Comments
• What is a Script? • Single-line and Block Comments
• #Requires Statement
Section 2: Running Scripts
• Execution Policies Section 5: Command Precedence
• Launching a script • Explore Command Precedence Rules

Section 3: Script Parameters


Section 6: Integrated Scripting Environment
• The Param Statement
• ISE

Microsoft Confidential 175


Module 5: Scripts

Section 1: Introduction to Scripts Lesson 1: What is a Script?

Microsoft Confidential 176


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 177


Example:
Simple script

Microsoft Confidential 178


Module 5: Scripts

Section 2: Running Scripts Lesson 1: Execution Policies

Microsoft Confidential 179


Execution Restricted
Policy • Default
• Scripts cannot be run
Levels • PowerShell interactive-mode only

AllSigned
• Runs a script only if signed
• Signature must be trusted on local machine

RemoteSigned
• Recommended Minimum
• Runs all local scripts
• Downloaded scripts must be signed by trusted source

Unrestricted
• All scripts from all sources can be run without signing

Microsoft Confidential 180


Execution AD Group Policy – Computer
• Affects all users on targeted computer
Policy • Edited through GPO Tools

Scope AD Group Policy – User


• Affects users targeted only
• Edited through GPO Tools
Apply Process
Execution • Console or ISE Command-line Parameter:
Highest
Priority
Policy Levels i.e.: c:\> powershell.exe –executionpolicy remotesigned
Wins
• Affects current PowerShell Host session only
at one or • Lost upon exit of session (i.e. host process)
more of these
Registry – User
5 scopes
• Affects current user only
• Stored in HKCU registry subkey

Registry – Computer
• Affects all users on computer
• Stored in HKLM registry subkey (Admin access needed to change)

Microsoft Confidential 181


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 182


Example:
Determine PS C:\> Get-ExecutionPolicy
Execution RemoteSigned
Policy in effect

183
Example: PS C:\> Get-ExecutionPolicy –List
Determine
Why Scope ExecutionPolicy
Execution ----- ---------------
Policy in MachinePolicy Undefined
effect UserPolicy Undefined Top most
Process Undefined takes
CurrentUser Undefined precedence
LocalMachine RemoteSigned

Effective
Policy

184
Example:
Set Execution
Policy - User

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

Apply setting to current user only,


default is current machine
185
Example:
Set Execution
Policy -
Computer

Start PowerShell with the "Run as administrator“ option


PS C:\> Set-ExecutionPolicy -ExecutionPolicy Unrestricted

186
Example: • Codesigning certificate
Script • Trusted by computer where script will run
Signing
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 Status Path


----------------- ------ ----
A4.. Valid ISECPUTime.ps1
Microsoft Confidential 187
Example:
Script
Before
Signing

Microsoft Confidential 188


Example:
Script
After
Signing

Script signature block

Microsoft Confidential 189


Module 5: Scripts

Section 2: Running Scripts Lesson 2: Launching a script

Microsoft Confidential 190


Running a Full path and file name
Script 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 191


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 192


Launching a script from outside PowerShell (cmd.exe)
Optionally Keeps
PowerShell Must be last parameter in command
Window open

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

Microsoft Confidential 193


Module 5: Scripts

Section 3: Script Parameters Lesson 1: The Param Statement

Microsoft Confidential 194


Param Statement
• Must be first statement in script, except for comments
• Parameter values are available to commands in script
Param Statement

Parameter Parameter Value

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


True

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


False

PS C:\scripts>
Microsoft Confidential 195
Module 5: Scripts

Section 4: Script Comments Lesson 1: Single-line and Block


Comments

Microsoft Confidential 196


Single-Line Comments

# Comment character

Microsoft Confidential 197


Block Comments

<# Block comment tags


#>

Microsoft Confidential 198


Module 5: Scripts

Section 4: Script Comments Lesson 2: #Requires Statement

Microsoft Confidential 199


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 200
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 .\test.ps1 : The script 'test.ps1' cannot be run because
it contained a "#requires" statement at line 1 for
#requires -Version 3 Windows PowerShell version 3.0. The version required by
Get-ChildItem c:\ -Hidden the script does not match the currently running version
of Windows PowerShell version 2.0.

Microsoft Confidential 201


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 .\RunAsAdminTest.ps1 : The script 'RunAsAdminTest.ps1'
cannot be run because it contains a "#requires"
#requires -RunAsAdministrator statement for
Get-ChildItem c:\ -Hidden running as Administrator. The current Windows
PowerShell session is not running as Administrator.
Start Windows
PowerShell by using the Run as Administrator option,
and then try running the script again.

Microsoft Confidential 202


Module 5: Scripts

Section 5: Command Precedence Lesson 1: Explore command


precedence rules

Microsoft Confidential 203


Command Lookup Precedence
• PowerShell rules that determine which command to run when there is more than
one command with the same name
Full Path (e.g. c:\scripts\BigFiles.ps1)

Alias

Function

Cmdlet

External commands

• 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 204
PS C:\> ping 2012r2-ms

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
Example: Reply from 10.0.1.210: bytes=32 time<1ms TTL=128
“Replace” Reply from 10.0.1.210: bytes=32 time<1ms TTL=128
Reply from 10.0.1.210: bytes=32 time<1ms TTL=128
another
command 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 Source Destination IPV4Address IPV6Address


instead of external ------ ----------- ----------- -----------
command
WIN8-WS 2012r2-ms 10.0.1.210
WIN8-WS 2012r2-ms 10.0.1.210
WIN8-WS 2012r2-ms 10.0.1.210
WIN8-WS 2012r2-ms 10.0.1.210
Microsoft Confidential 205
#Run normal cmdlet
PS C:\> Get-Process system

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


Example: ------- ------ ----- ----- ----- ------ -- -----------
Module 1427 0 140 4232 16 4 System

Qualify
Command #Create function with same name
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 NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName


------- ------ ----- ----- ----- ------ -- -----------
1427 0 140 4232 16 4 System
Microsoft Confidential 206
Module 5: Scripts

Section 6: Integrated Scripting Lesson 1: ISE


Environment (ISE)

Microsoft Confidential 207


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 Name Install State


------------ ------- -------------
[X] Windows PowerShell PowerShellRoot Installed
[X] Windows PowerShell 3.0 PowerShell Installed
[ ] Windows PowerShell 2.0 Engine PowerShell-V2 Available
[ ] Windows PowerShell ISE PowerShell-ISE Available

PS C:\> Add-WindowsFeature PowerShell-ISE

Success Restart Needed Exit Code Feature Result


------- -------- ---------------- ----------------
True No Success {Windows PowerShell ISE}
Microsoft Confidential 208
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 209


Integrated Context Sensitive Help

Context-Sensitive Help ISE Executes Get-Help cmdlet


• Highlight text • -ShowWindow parameter used
• Choose Help from menu or Press • Command executed visible in
F1 Command pane

Microsoft Confidential 210


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 211


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 212


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 213


Example: • Cmdlet or function parameters appear in a pop-out window
IntelliSense • Parameter value types shown in a secondary window
Parameters

Microsoft Confidential 214


Example: Some cmdlet parameters display parameter values
IntelliSense
Parameter
Arguments

Microsoft Confidential 215


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 216


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 217


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 218


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 219


Example:
ISE Snippet Insertion
Click Enter to choose snippet
and insert code

Ctrl-J
or
Edit -> Start Snippets
Microsoft Confidential 220
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 221


Module 5: Scripts

Lab

Microsoft Confidential 222


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 223


Module 6: Help System

Module Overview

Microsoft Confidential 224


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 225


Module 6: Help System

Section 1: Beyond Cmdlet help Lesson 1: Getting help for


PowerShell concepts

Microsoft Confidential 226


Example: Conceptual help topic names start with “about_”
Concept help
in the console PS C:\> Get-Help about_

Name Category Module Synopsis


---- -------- ------ --------
about_Aliases HelpFile Describes how to...
about_Arithmetic_Operators HelpFile Describes the op...
about_Arrays HelpFile Describes arrays...
about_Assignment_Operators HelpFile Describes how tp...
about_Automatic_Variables HelpFile Describes variab...
...

Microsoft Confidential 227


1. Type Get-Help about_ in the console pane
Example: 2. Click on an item in the result set
Concept 3. Press F1
help in the
ISE

2
3

Microsoft Confidential 228


Module 6: Help System

Section 2: Managing the help Lesson 1: Updatable Help


system

Microsoft Confidential 229


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 Help readily updated by authors
o No need to ship updates with Service Packs or new module download
o Module authors designate URL for help download in module manifest
o Module author provides web site URL targets

Note: PowerShell Modules will be discussed later.

Microsoft Confidential 230


Update-Help Diagram (Internet Connected)

Internet Update-Help

Microsoft Confidential 231


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 232


Update-Help Diagram (Not Internet Connected)
Save-Help –DestinationPath

Internal
Internet Folder
Location

Internal machines
do not need
Internet access

Optional Default
source path location
GPO Setting

Microsoft Confidential
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 computers without Internet Access (with GPO source path):

PS C:\> Update-Help

GPO Setting:
• Computer > Policies > Administrative Templates > Windows Components > Windows PowerShell
• Enable "Set the default source path for Update-Help."
Microsoft Confidential 234
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 235


Module 6: Help System

Section 3: Using the help system Lesson 1: Using Help

Microsoft Confidential 236


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 237


Module 6: Help System

Section 3: Using the help system Lesson 2: Comment-based help


topics for functions and scripts

Microsoft Confidential 238


Function/Script Comment-based Help
Special help comment keywords can be used to write Get-Help topics for
functions and scripts

Syntax
# .< help keyword>
# <help content>

-or -

<#
.< help keyword>
< help content>
#>
Microsoft Confidential 239
Keywords

.SYNOPSIS .NOTES
.DESCRIPTION .LINK
.PARAMETER <parameter name> .COMPONENT
.EXAMPLE .ROLE
.INPUTS .FUNCTIONALITY
.OUTPUTS

Microsoft Confidential 240


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 241


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 242
Module 6: Help System

Lab

Microsoft Confidential 243


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 244


Module 7: Object Models

Module Overview

Microsoft Confidential 245


Module 7: Object Models

Section 1: Objects in PowerShell Section 2: Object Models


• What is an object? • Where do TYPES come from?
• Identify PROPERTIES and METHODS • ISE IntelliSense and Member
for an object Completion
• Identify the TYPE of an object

Microsoft Confidential 246


Module 7: Object Models

Section 1: Objects in PowerShell Lesson 1: What is an object?

Microsoft Confidential 247


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 248


The Bike Parts How to use
Object Properties Methods
Front Wheel Pedal

Back Wheel Brake

Pedals Steer Left

Steer Right
Colour
Wheelie
Size

Microsoft Confidential Microsoft Confidential 249


Objects and Type: Object Template Object: Instances of a type
Types

$Bike1.Size = "Large"
$Bike1.Colour = "Green"
Bike
Size Property
Colour Property
$Bike3.Size = "Medium"
$Bike3.Colour = "Yellow"
Brake() Method $Bike3.Wheelie()
Wheelie() Method $Bike2.Size = "Small"
$Bike2.Colour = "Blue"

Microsoft Confidential 250


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 251


Module 7: Object Models

Section 1: Objects in PowerShell Lesson 2: Identify PROPERTIES


and METHODS for an object

Microsoft Confidential 252


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 253


PS C:\> Get-ChildItem c:\windows\windowsupdate.log | Get-Member
Example:
Find object TypeName: System.IO.FileInfo

members Name MemberType Definition


---- ---------- ----------
AppendText Method System.IO.StreamWriter AppendText()
Create Method System.IO.FileStream Create()
CreateText Method System.IO.StreamWriter CreateText()
Decrypt Method void Decrypt()
Delete Method void Delete()
...
Attributes Property System.IO.FileAttributes Attributes
CreationTime Property datetime CreationTime {get;set;}
CreationTimeUtc Property datetime CreationTimeUtc {get;set;}
Directory Property System.IO.DirectoryInfo Directory {get;}
...

Microsoft Confidential 254


PS C:\> Get-ChildItem c:\windows\windowsupdate.log | Get-Member
Example:
Find object TypeName: System.IO.FileInfo

members Name MemberType Definition


---- ---------- ----------
AppendText Method System.IO.StreamWriter AppendText()
Create Method System.IO.FileStream Create()
CreateText Method System.IO.StreamWriter CreateText()
Decrypt Method void Decrypt()
Delete Method void Delete()
...
Attributes Property System.IO.FileAttributes Attributes
CreationTime Property datetime CreationTime {get;set;}
CreationTimeUtc Property datetime CreationTimeUtc {get;set;}
Directory Property System.IO.DirectoryInfo Directory {get;}
...

Microsoft Confidential 255


Example: Object stored in a variable
Retrieving PS C:\> $csvhash = Get-FileHash .\iExploreProcesses.csv
Property
using dot
notation
(Variable)

Microsoft Confidential 257


Example: Pipe variable to Get-Member to list properties
Retrieving PS C:\> $csvhash | Get-Member
Property
using dot TypeName: Microsoft.Powershell.Utility.FileHash
notation Name MemberType Definition
(Variable) ---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Algorithm NoteProperty System.String Algorithm=SHA256
Hash NoteProperty System.String Hash=207...

Dot (.) followed by the property name


PS C:\> $csvhash.Hash
207267C4B159E53C2272E6574DD89C78CF83648133698D793AB727D8CDF9
Microsoft Confidential 258
Example: Object property can also be accessed using parenthesis
Retrieving PS C:\> (Get-FileHash .\iExploreProcesses.csv) | Get-Member
Property
TypeName: Microsoft.Powershell.Utility.FileHash
using dot
notation Name MemberType Definition
(Command) ---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Algorithm NoteProperty System.String Algorithm=SHA256
Hash NoteProperty System.String Hash=207...

Dot (.) followed by the property name


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

Microsoft Confidential 259


PS C:\> (Get-Process -Name spoolsv) | Get-Member -MemberType Method
Example:
Call TypeName: System.Diagnostics.Process
method Name MemberType Definition
---- ---------- ----------
on an BeginErrorReadLine Method void BeginErrorReadLine()
object BeginOutputReadLine Method void BeginOutputReadLine()
CancelErrorRead Method void CancelErrorRead()
CancelOutputRead Method void CancelOutputRead()
Close Method void Close()
CloseMainWindow Method bool CloseMainWindow()
CreateObjRef Method System.Runtime...
Dispose Method void Dispose(),
Kill Method void Kill()
...

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


PS C:\> (Get-Process -Name spoolsv).Kill()
Microsoft Confidential 260
Module 7: Object Models

Section 1: Objects in PowerShell Lesson 3: Identify the TYPE of an


object

Microsoft Confidential 261


PS C:\> Get-Date | Get-Member
Example 1:
Find the object TYPE TypeName: System.DateTime
returned by the
Get-Date cmdlet Name
----
MemberType
----------
Definition
----------
Add Method datetime Add(timespan value)
AddDays Method datetime AddDays(double value)
AddHours Method datetime AddHours(double value)

• Get-Member displays the TYPE name

Microsoft Confidential 262


PS C:\> (Get-Date).GetType()
Example 2:
Find the object TYPE IsPublic IsSerial Name
returned by the -------- -------- ----
Get-Date cmdlet True True DateTime

• GetType() METHOD retrieves the TYPE name


• Available on ALL objects in PowerShell

Microsoft Confidential 263


Module 7: Object Models

Section 2: Object Models Lesson 1: Where do TYPES come


from?

Microsoft Confidential 264


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 265


Module 7: Object Models

Section 2: Object Models Lesson 2: ISE IntelliSense and


Member Completion

Microsoft Confidential 267


Pop-out window shows object members

Example:
IntelliSense Object
Members
Property

Method

Microsoft Confidential 268


Module 7: Object Models

Lab

Microsoft Confidential 269


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 270


Module 8: Operators 1

Module Overview

Microsoft Confidential 271


Module 8: Operators 1

Section 1: Comparison Section 3: Range


• Comparison Operators • Range Operators

Section 2: Logical Section 4: Numeric Multipliers


• Logical Operators • Numeric Multipliers

Microsoft Confidential 272


Module 8: Operators 1

Section 1: Comparison Operators Lesson 1: Comparison Operators

Microsoft Confidential 273


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 274


Comparison Operators - Basic
No Wildcards
-eq Equals -ceq
-ne Not Equals -cne
-gt Greater Than -cgt
-ge Greater Than or Equal To -cge
-lt Less Than -clt
-le Less Than or Equal To -cle

Case-Sensitive
Version

Microsoft Confidential 275


PS C:\> 1 -eq 1
Example 1:
True
Basic operators
PS C:\> 1 -eq 2
False

PS C:\> 10 -gt 20
False

PS C:\> 10 -gt 5
True

Microsoft Confidential 276


PS C:\> 'PowerShell' -gt 'CMDPrompt'
Example 2:
True
Basic operators
PS C:\> 'a' –lt 'aa'
True

PS C:\> $service = Get-Service bits


PS C:\> $service.Status -eq 'Running'
True

Microsoft Confidential 277


Comparison Operators - Wildcards

-like Equals with wildcards -clike


-notlike Not Equals with wildcards -cnotlike

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


PS C:\> 'Pear' -eq 'p*'
Example:
False
-Like
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 0 8972 628 13 51.33 4 System

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


False
Must be 7 chars followed
Microsoft Confidential
by zero or more
279
Comparison Operators – Regular Expressions
See Get-Help about_Regular_Expressions

-match Regular Expression comparison -cmatch


-notmatch Regular Expression NOT comparison -cnotmatch

Case-Sensitive
Version

Microsoft Confidential 280


PS C:\> 'Digit 5 in this string' -match '\d'
Example:
True
-Match
PS C:\> 'hello there' -match '^there'
False

\d - Digit

^ - Start of Text

See Get-Help about_Regular_Expressions for syntax

Microsoft Confidential 281


Comparison Operators – Array/Collection Containment
Always results in Boolean (True/False) Case-Sensitive
Version

Array on left, Singleton on Right


-contains Array Contains single -ccontains
-notcontains Array not Contains single -cnotcontains

Singleton on left, Array on Right


-in Single in Array -cin
-notin Single not in Array -cnotin
-in, -notin introduced by PowerShell v3.0

Case-Sensitive
Microsoft Confidential
Version 282
PS C:\> 1,2,3 -contains 2
Example:
True
Array
Containment 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 283


PS C:\> (Get-Process).Name -contains 'Notepad'
Example:
True
Array
Containment PS C:\> $ServerList = Get-Content .\textfile.txt
PS C:\> $ServerList -contains 'Server10'
True

PS C:\> 'Server20' -in $ServerList


True

Microsoft Confidential 284


PS C:\> "abcde" -eq "ABCDE"
Example:
True
Operator Case
Sensitivity 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 285
Module 8: Operators 1

Section 2: Logical Operators Lesson 1: Logical Operators

Microsoft Confidential 286


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.

-not or ! Negates the statement that follows it.

Microsoft Confidential 287


Examples: PS C:\> (4 –lt 8) –and (5 –lt 10)
True
-and
-or PS C:\> (4 –lt 8) –or (5 –lt 4)
-xor True
-not
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 288


Module 8: Operators 1

Section 3: Range Operators Lesson 1: Range Operators

Microsoft Confidential 289


Range Operator
Numerical

PS C:\> 1..10 PS C:\> 11..20 PS C:\> 5..-5


1 11 5
2 12 4
3 13 3
4 14 2
5 15 1
6 16 0
7 17 -1
8 18 -2
9 19 -3
10 20 -4
-5

Microsoft Confidential 290


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


---- ------------- ------ ----
d---- 22/08/2013 11:36 AM AdvancedInstallers
d---- 20/05/2014 8:22 AM AppLocker
d---- 19/10/2013 8:19 AM appmgmt
d---- 8/04/2014 7:38 PM ar-SA
d---- 19/10/2013 12:05 PM BestPractices
...

Microsoft Confidential 291


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 LastWriteTime Length Name


---- ------------- ------ ----
d---- 23/08/2013 1:36 AM ja-JP
d---- 23/08/2013 1:36 AM zh-CN
-a--- 23/08/2013 5:12 AM 25600 jnwmon.dll
-a--- 22/08/2013 9:03 PM 142848 joy.cpl
-a--- 22/08/2013 9:11 PM 53760 jsproxy.dll
-a--- 22/08/2013 9:01 PM 429568 zipfldr.dll
...

Microsoft Confidential 292


Module 8: Operators 1

Section 4: Numeric Multipliers Lesson 1: Numeric Multipliers

Microsoft Confidential 293


Numeric Byte Multipliers
• Convenient byte multiples
• Commonly-used powers of 2
• Case-insensitive
Multiplier Meaning Example
kb kilobyte (n * 1024) PS C:\> 2kb
2048
mb megabyte (n * 1024 x 1024) PS C:\> 100mb
104857600
gb gigabyte (n * 1024 x 1024 x 1024) PS C:\> 1.5gb
1610612736
tb terabyte (n * 1024 x 1024 x 1024 x 1024) PS C:\> 1tb
1099511627776
pb petabyte (n * 1024 x 1024 x 1024 x 1024 x PS C:\> 1pb
1024) 1125899906842624
Microsoft Confidential 294
Module 8: Operators 1

Lab

Microsoft Confidential 295


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 296


Module 9: Pipeline 2

Module Overview

Microsoft Confidential 297


Module 9: Pipeline 2

Section 1: Pipeline Objects Section 3: Pipeline Processing


• Pipeline Variable • Begin, Process and End Blocks

Section 2: Pipeline Cmdlets Section 4: Cmdlet Parameter Pipeline Input


• Other Object Cmdlets • Two ways to accept pipeline input

Microsoft Confidential 298


Module 9: Pipeline 2

Section 1: Pipeline Objects Lesson 1: Pipeline Variable

Microsoft Confidential 299


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 300
Module 9: Pipeline 2

Section 2: Pipeline Cmdlets Lesson 1: More Object Cmdlets

Microsoft Confidential 301


Other Object Cmdlets

ForEach-Object Performs an operation against each item.


Aliases:
• %
• ForEach
Where-Object Filters objects in the pipeline
Aliases:
• ?
• Where

Microsoft Confidential 302


Example:
ForEach-Object

Take an action on each object


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

Hello Netlogon
Hello Netman
Hello netprofm
Hello NetTcpPortSharing

Microsoft Confidential 303


PS C:\> Get-ChildItem -path *.txt |
Where-Object {$_.length -gt 10kb} |
Sort-Object -property Length |
Example: Format-Table -property name, length
Pipeline
Filtering (FileInfo)
with Where- Get-ChildItem -path *.txt (*.txt)
Object (FileInfo)
(*.txt)
Where-Object {$_.length -gt 10kb} (Length > 10240)
(FileInfo)
(*.txt)
Sort-Object -property Length (Length > 10240)
(Sorted by length)
(FileInfo)
Format-Table -property name, (*.txt)
length
(Length > 10240)
(Sorted by length)
(Formatted in table) 304
• Simplified filtering syntax
Example: • Syntax emulates natural language
Where-Object • PowerShell v3.0+
(Simple syntax)
• Note: Multiple filter conditions need full syntax

PowerShell v1.0+
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 No compound
conditions with
simplified syntax

Microsoft Confidential 305


Example: Filter output with Where-Object (~11 milliseconds)
Filtering with PS C:\> Get-Process |
Parameters vs. Where- Where-Object {$_.Name -eq "explorer"}
Object

Filter output with parameters (~4 milliseconds)


PS C:\> Get-Process -Name explorer

PowerShell Proverb: “Filter left. Format Right.”

Microsoft Confidential 306


Retrieve single property from collection without using ForEach-Object

Example: Single level


Automatic PS C:\> (Get-Process).ID
Member 4300 Doesn’t work in PowerShell
Enumeration 8844 v1.0 and v2.0
8812

Multiple levels deep


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

Count Name Group


----- ---- -----
4174 Tuesday {Tuesday, Tuesday, Tuesday...}
4349 Monday {Monday, Monday, Monday...}

Microsoft Confidential 307


Module 9: Pipeline 2

Section 3: Pipeline Processing Lesson 1: Begin, Process and End


Blocks

Microsoft Confidential 308


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


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 312


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 313
function My-Function
{
Example: Begin
Named {
Remove-Item .\Events.txt
Blocks 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 314


Module 9: Pipeline 2

Section 4: Cmdlet Parameter Lesson 1: Two ways to accept


Pipeline Input pipeline input

Microsoft Confidential 315


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 316


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? false
Position? 1
Default value Local computer
Accept pipeline input? True (ByValue, ByPropertyName)
Accept wildcard characters? false

Microsoft Confidential 317


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 318


Restart-Computer ComputerName Parameter
PS C:\> Get-Help Restart-Computer -Parameter ComputerName
Example:
Pipeline -ComputerName <String[]>
Input
Specifies one or more remote computers. The default is ...
ByValue
Required? false
Position? 1
Default value Local computer
Accept pipeline input? True (ByValue, ByPropertyName)
Accept wildcard characters? 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".

320
Pipeline Input ByPropertyName

For parameters that accept pipeline input ByPropertyName,


piped objects properties will bind:

To parameter(s) of the same name

Microsoft Confidential 321


Restart-Computer ComputerName Parameter
PS C:\> Get-Help Restart-Computer -Parameter ComputerName
Example:
Pipeline -ComputerName <String[]>
Input
Specifies one or more remote computers. The default is ...
ByProperty
Required? false
Position? 1
Default value Local computer
Accept pipeline input? True (ByValue, ByPropertyName)
Accept wildcard characters? 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".
322
The Parameter Binding Steps
User Defines
1. Bind all named parameters
2. Bind all positional parameters
3. Bind from the pipeline by value with exact match
4. Bind from the pipeline by value with conversion
5. Bind from the pipeline by name with exact type match
6. Bind from the pipeline by name with type conversion

Microsoft Confidential 324


Module 9: Pipeline 2

Lab

Microsoft Confidential 325


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 326


Module 10: Providers

Module Overview

Microsoft Confidential 327


Module 10: Providers

Section 1: Providers Introduction Section 3: Provider Cmdlets


• What are Providers? • Provider Cmdlet
• Drive Cmdlets
Section 2: Built-in Providers • Item Cmdlets
• Built-in Providers
• Item Property Cmdlets
• Content Cmdlets
• Location Cmdlets
• Path Cmdlets

Microsoft Confidential 328


Module 10: Providers

Section 1: Providers Introduction Lesson 1: What are Providers?

Microsoft Confidential 329


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 330


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 331


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 332


Module 10: Providers

Section 2: Built-in Providers Lesson 1: Built-in Providers

Microsoft Confidential 333


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 334


Module 10: Providers

Section 3: Provider Cmdlets Lesson 1: Provider Cmdlets

Microsoft Confidential 335


Example: Returns a table of installed providers, their capabilities and drives
Get-PSProvider PS C:\> Get-PSProvider

Name Capabilities Drives


---- ------------ ------
Alias ShouldProcess {Alias}
Environment ShouldProcess {Env}
FileSystem Filter, ShouldProcess, Credentials {C}
Function ShouldProcess {Function}
Registry ShouldProcess, Transactions {HKLM, HKCU}
Variable ShouldProcess {Variable}
Certificate ShouldProcess {Cert}
WSMan Credentials {WSMan}

336
Provider Capabilities
Name Description

Credentials Credentials can be passed to provider

Exclude Items can be excluded from data store based on a wildcard string

ExpandWildcards Wildcards are handled within a provider internal path

Filter Additional filtering based on some provider-specific string is supported

Include Items can be included in data store based on a wildcard string

None Only features provided by base class and implemented interfaces are supported

ShouldProcess Allows use of the WhatIf and Confirm (Risk Mitigation) parameters

Transactions Allows user to accept/reject actions of provider cmdlets

Microsoft Confidential
Module 10: Providers

Section 3: Provider Cmdlets Lesson 2: Drive Cmdlets

Microsoft Confidential 338


Example: Returns drives in current session
Get-PSDrive PS C:\> Get-PSDrive

Name Used (GB) Free (GB) Provider Root


---- --------- --------- -------- ----
Alias Alias
C 206.81 16.00 FileSystem C:\
Cert Certificate \
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan

339
Example: Creates a user-defined drive
New-PSDrive PS C:\> New-PSDrive -Name HKCR -PSProvider Registry
Remove-PSDrive -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

340
Module 10: Providers

Section 3: Provider Cmdlets Lesson 3: Item Cmdlets

Microsoft Confidential 341


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 342


Item Cmdlets
Name Example

Remove-Item 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"

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


Marketing

Microsoft Confidential 343


Module 10: Providers

Section 3: Provider Cmdlets Lesson 4: ItemProperty Cmdlets

Microsoft Confidential 344


ItemProperty Cmdlets
Name Example

Get-ItemProperty PS C:\> Get-ItemProperty -Path


HKLM:\SOFTWARE\Microsoft\PowerShell\1

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


HKLM:\Software\MyAppRev2 -Name MyProperty

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


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

Clear-ItemProperty PS C:\> Clear-ItemProperty -Path


HKLM:\Software\MyCompany\MyApp -Name Options

Microsoft Confidential 345


ItemProperty Cmdlets
Name Example

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

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


-Name config -NewName oldconfig

Microsoft Confidential 346


Module 10: Providers

Section 3: Provider Cmdlets Lesson 5: Content Cmdlets

Microsoft Confidential 347


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

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


Add-Content final.xml -Force -Encoding UTF8

Clear-Content 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 348


Module 10: Providers

Section 3: Provider Cmdlets Lesson 6: Location Cmdlets

Microsoft Confidential 349


Location Cmdlets

Name Example

Get-Location PS C:\> Get-Location


C:\

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


PS HKLM:\SOFTWARE>

Microsoft Confidential 350


Module 10: Providers

Section 3: Provider Cmdlets Lesson 7: Path Cmdlets

Microsoft Confidential 351


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 352


Path Cmdlets

Name Example

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


HKEY_LOCAL_MACHINE\Software\Microsoft

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


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

Microsoft Confidential 353


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 354


Module 10: Providers

Lab

Microsoft Confidential 355


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 356


Module 11: Variables and
Data Types

Module Overview

Microsoft Confidential 357


Module 11: Variables and Data Types
Section 1: Variables Section 4: Other Types
• What are variables? • Other Types

Section 2: Kinds of variables Section 5: Using Types


• Automatic Variables • Using Types
• User-Defined Variables
Section 6: Type Operators
• Type Operators
Section 3: String Type
• Literal Strings Section 7: Parsing
• Expandable Strings • Parsing Modes
• Here Strings • Escape Character
• Variable Sub-Expression • Stop Parsing

Microsoft Confidential 358


Module 11: Variables and Data
Types

Section 1: Variables Lesson 1: What are Variables?

Microsoft Confidential 359


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 360
Module 11: Variables and Data
Types

Section 2: Kinds of Variables Lesson 1: Automatic Variables

Microsoft Confidential 361


Automatic Variables
User Defines
• Built-in

• Created and maintained by PowerShell

• Store PowerShell state

Microsoft Confidential 362


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 User’s home directory
PS C:\> $Host Current host application for PowerShell
PS C:\> $null NULL or empty value
PS C:\> $PSHOME Full path of installation directory for PowerShell
PS C:\> $true Represents TRUE in commands
PS C:\> $false Represent FALSE in commands
Microsoft Confidential 363
Module 11: Variables and Data
Types

Section 2: Kinds of Variables Lesson 2: User-Defined Variables

Microsoft Confidential 364


User-Defined Variables

• Created and maintained by user

• Exist only in current session

• Lost when session is closed

Microsoft Confidential 365


Variable Cmdlets

Name Example

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

Clear-Variable PS C:\> Clear-Variable -Name Processes

Remove-Variable 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 366


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 367


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 368


Example: PS C:\> $svcs = Get-Service
User- #or
Defined PS C:\> Get-Service -OutVariable svcs
Variable #or
PS C:\> New-Variable -Name svcs -Value (Get-Service)

PS C:\> $svcs

Status Name DisplayName


------ ---- -----------
Stopped AeLookupSvc Application Experience
Stopped ALG Application Layer Gateway Service
Running AppIDSvc Application Identity
Running Appinfo Application Information
... 369
Variables and Data Types

Remember, in PowerShell:

• Everything is an OBJECT
• Each OBJECT has a TYPE
• Variables reference OBJECTS

Microsoft Confidential 370


Module 11: Variables and Data
Types

Section 3: String Type Lesson 1: Literal Strings

Microsoft Confidential 371


Example: Create a variable
Literal Strings 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

372
Module 11: Variables and Data
Types

Section 3: String Type Lesson 2: Expandable Strings

Microsoft Confidential 373


Example: Create a variable
Expandable PS C:\> $a = 123
Strings

Include the variable in an expandable string (double-quotes)


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

Notice that $a is expanded


PS C:\> $b
As easy as 123

374
Module 11: Variables and Data
Types

Section 3: String Type Lesson 3: Here Strings

Microsoft Confidential 375


Example: Literal String Expandable String
Literal or PS C:\> $lString = ' PS C:\> $eString = "
Expandable As As
easy easy
String as as
Spanning $a $a
Multiple ' "
Lines
PS C:\> $lString PS C:\> $eString
As As
easy easy
as as
$a 123

376
• Simplify use of longer, more complex string assignments
Example: • Here String can contain quotes, @ sign, etc.
Here Strings
Literal Here String Expandable Here String
PS C:\> $lhere = @' PS C:\> $ehere = @"
As As
'easy' "easy"
as as
$a $a
'@ "@

PS C:\> $lhere PS C:\> $ehere


As As
' easy ' "easy"
as as
$a 123

377
Module 11: Variables and Data
Types

Section 3: String Type Lesson 4: Variable


Sub-expression

Microsoft Confidential 378


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 379


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

Example:
Variable Determine the variable type
Sub-expression 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
380
Module 11: Variables and Data
Types

Section 4: Other Types Lesson 1: Other types

Microsoft Confidential 381


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.DateTime Stores date and time values

Microsoft Confidential 382


Module 11: Variables and Data
Types

Section 5: Using Types Lesson 1: Using types

Microsoft Confidential 383


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 384


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 385


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:\> [int]$var1 = 1.3
PS C:\> $var1 PS C:\> $var1
1 1

PS C:\> $var1 = 1.2 PS C:\> $var1 = 1.2


PS C:\> $var1 PS C:\> $var1
1.2 1

Microsoft Confidential 386


PS C:\> [int]$var1 = 123.5
Example:
PS C:\> $var1
Strong 124
Typing a
variable 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."

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


A type can be used in PowerShell using square brackets
PS C:\> [char]
Example:
Discover IsPublic IsSerial Name BaseType
-------- -------- ---- --------
Static True True Char System.ValueType
Members
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
389
Example: Use range operator and Char type to convert numbers to ASCII
Print ASCII Characters
table using PS C:\> 33..255 | ForEach-Object {
PowerShell Write-Host "Decimal: $_ = Character: $([Char]$_)"
}

Decimal: 33 = Character: !
Decimal: 34 = Character: "
Decimal: 35 = Character: #
Decimal: 36 = Character: $
Decimal: 37 = Character: %
Decimal: 38 = Character: &
Decimal: 39 = Character: '
...

390
Module 11: Variables and Data
Types

Section 6: Type Operators Lesson 1: Type Operators

Microsoft Confidential 391


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 392


Type Operators – Type Cast via Operator
Operator Example
-as PS C:\> "27/12/2013" -as [datetime]

Friday, 27 December 2013 12:00:00 AM

Same Result
PS C:\> [datetime]"27/12/2013"

Friday, 27 December 2013 12:00:00 AM

Microsoft Confidential 393


Module 11: Variables and Data
Types

Section 7: Parsing Lesson 1: Parsing Modes

Microsoft Confidential 394


Parsing Modes
PowerShell
• User Defines 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 395


Parsing Mode Examples
User Defines
Example Mode Result
2+2 Expression 4
Write-Output –InputObject 2+2 Argument "2+2"
Write-Output –InputObject (2+2) Expression 4
$a = 2+2 ; $a Expression 4
Write-Output $a Expression 4
Write-Output $a/H Argument "4/H"
Get-ChildItem "C:\Program Files" Expression

Microsoft Confidential 396


Example: Get-Date is a token interpreted as an ARGUMENT by the parser
Turn Get-Date is not treated as an expression
Argument PS C:\> Write-Host "The date is: Get-Date"
Mode into The date is: Get-Date
Expression
Mode with $ changes the parsing mode to EXPRESSION
$()
PS C:\> Write-Host "The date is: $(Get-Date)"
The date is: 1/3/2013 11:03:53

397
Example: Store a string representing a Cmdlet name in a variable
Turn Call the command by using the ampersand (&) character
Expression PS C:\> $cmd = "Get-Process"
Mode into PS C:\> $cmd
Get-Process
Argument
Mode with & PS C:\> & $cmd

Handles NPM(K) PM(K) WS(K) Id Name


------- ------ ----- ----- ----- ------
333 18 8032 8.80 8244 AcroRd32
413 39 155844 131.89 10140 AcroRd32
84 8 1128 0.13 2228 armsvc

398
Module 11: Variables and Data
Types

Section 7: Parsing Lesson 2: Escape Character

Microsoft Confidential 399


Escape Character
• Assigns a special interpretation to characters that follow

• Backtick (grave accent)

• ASCII 96

Microsoft Confidential 400


Examples: Force a special PS C:\> $a = 123
Backtick character to be literal PS C:\> Write-Host "`$a is $a"
Uses $a is 123
Force a literal PS C:\> Write-Host "There are two
character to be special line breaks`n`nhere. "
Limited List (next slide) There are two line breaks

here.
Line continuation
Must be last char

401
Special Characters
Character Description Note:
`0 Null These characters are case-sensitive and
`a Alert only have effect within double quotes
`b Backspace
`f Form feed
`n New line
`r Carriage return
`t Horizontal tab
`v Vertical tab

Microsoft Confidential
Module 11: Variables and Data
Types

Section 7: Parsing Lesson 3: Stop Parsing

Microsoft Confidential 403


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 404


Parsing and special characters can make external commands challenging
PS C:\> icacls X:\VMS /grant Dom\HVAdmin:(CI)F
Example:
Stop CI : The term 'CI' is not recognized as the name
Parsing of a cmdlet, function, script file, or operable
External program.
Command Parenthesis cause issue
Arguments
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
405
Module 11: Variables and
Data Types

Lab

Microsoft Confidential 406


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 407


Module 12: Operators 2

Module Overview

Microsoft Confidential 408


Module 12: Operators 2

Section 1: Arithmetic Operators Section 4: Split, Join, and Replace


Operators
• Split Operator
Section 2: Assignment Operators • Join Operator
• Replace Operator

Section 3: Binary Operators Section 5: Format Operator

Microsoft Confidential 409


Module 12: Operators 2

Section 1: Arithmetic Operators Lesson 1: Arithmetic Operators

Microsoft Confidential 410


Arithmetic Operators
Operator Description Example(s) Result(s)
+ Adds integers; concatenates strings, arrays, and hash 6 + 2 8
tables "file" + "name" filename
- Subtracts values 6 - 2 4
- Indicates negative value -6 + 2 -4
* Multiplies integers; copies strings and arrays 6 * 2 12
"ABC" * 3 ABCABCABC
/ Divides values 6/2 3
% Returns remainder of division (modulus) 7%2 1
-shl Shift-left bitwise 100 -shl 2 400
-shr Shift-right bitwise 100 -shr 1 50

100 in binary is 1100100 100 in binary is 1100100


-shl shifts digits n chars left -shr shifts digits n chars right
400 in binary is 110010000 50 in binary is 110010
Microsoft Confidential 411
Module 12: Operators 2

Section 2: Assignment Operators Lesson 1: Assignment Operators

Microsoft Confidential 412


Assignment Operators

Operator Description 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 413
Module 12: Operators 2

Section 3: Binary Operators Lesson 1: Binary Operators

Microsoft Confidential 414


Binary Operators
Operator Description Example(s) Binary Format
-bAnd Bitwise AND 10 -band 3 1010 (10)
0011 (3)
-------- bAND
0010 (2)
-bOr Bitwise OR 10 -bor 3 1010 (10)
(inclusive) 0011 (3)
--------- bOR
1011 (11)
-bXor Bitwise OR 10 -bxor 3 1010 (10)
(exclusive) 0011 (3)
------- bXOR
1001 (9)
-bNot Bitwise NOT -bnot 10 0000 1010 (10)
---------------- bNOT
1111 0101 (-11)

Microsoft Confidential 415


Module 12: Operators 2

Section 4: Split, Join & Replace Lesson 1: Split Operator


Operators

Microsoft Confidential 416


Split Operator
Description Example(s)
Unary split operator: PS C:\> -split "1 a b"
-split <string> 1
a
Note: b
• Example splits on space as delimiter
Binary split operator: PS C:\> "1,a b" -split ","
<string> -split <delimiter> 1
a b
Note:
• Example splits on comma as delimiter

The -Split operator uses a Regular


Expression for the delimiters
Microsoft Confidential 417
Module 12: Operators 2

Section 4: Split, Join & Replace Lesson 2: Join Operator


Operators

Microsoft Confidential 418


Join Operator
Description Example(s)
Unary join operator: PS C:\> -join ("a", "b", "c")
-join <string[]> abc

Binary join operator: PS C:\> "Windows", "PowerShell", "4.0" –join [char]2


String[]> -Join<Delimiter> Windows☻PowerShell☻4.0

PS C:\> "How","are","you","doing?" -join " "


How are you doing?

Microsoft Confidential 419


Module 12: Operators 2

Section 4: Split, Join & Replace Lesson 3: Replace Operator


Operators

Microsoft Confidential 420


Replace Operator
Description Example(s)
Binary replace operator: PS C:\> "Windows PowerShell 4.0" –replace "4.0","5.0"
<String[]> -Replace <Delimiter> Windows PowerShell 5.0

Microsoft Confidential 421


Module 12: Operators 2

Section 5: Format Operator Lesson 1: Format Operator

Microsoft Confidential 422


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 423


Format Operator – Quick Examples

PS C:\> $MyArray = 'Smith','John',123.456

PS C:\> “Custom Text" -f $MyArray


Custom Text

PS C:\> "First name is: {1} Last name is: {0}" -f $MyArray
First name is: John Last name is: Smith

PS C:\> "{2}" -f $MyArray


123.456

PS C:\> "Using a Format Specifier {2:N1}" -f $MyArray


Using a Format Specifier 123.5

Microsoft Confidential 424


Format Operator – Index Example
Index Positions

Ordered using index 1 3 4


0 2

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 425


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

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

Microsoft Confidential 426


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%

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

Microsoft Confidential 427


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

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

Microsoft Confidential 428


Format Operator – FormatString Example 3

Round number to 2
decimal places

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

3.14

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

Microsoft Confidential 429


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

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

Microsoft Confidential 430


Format Operator – FormatString Example 5

Format DateTime

PS C:\> '{0:hh}:{0:mm}:{0:ss}' -f (get-date)

11:35:16

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

Microsoft Confidential 431


Module 12: Operators 2

Lab

Microsoft Confidential 432


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 433


Module 13: Arrays

Module Overview

Microsoft Confidential 434


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 435


Module 13: Arrays

Section 1: Array Introduction Lesson 1: What Are Arrays?

Microsoft Confidential 436


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 437


Module 13: Arrays

Section 2: Using Arrays Lesson 1: Creating Arrays

Microsoft Confidential 438


Arrays can be created in a number of ways:
Example:
Creating Cmdlets that return multiple items
Arrays 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 = @()

439
Module 13: Arrays

Section 2: Using Arrays Lesson 2: Accessing Array Items

Microsoft Confidential 440


Display all items in an array Display first 3 items in array
PS C:\> $array PS C:\> $array[0..2]
Example: 22 22
Accessing 5 5
Array Items 10 10
8
12 Display first item and last item in array
9 PS C:\> $array[0,-1]
8 22
First item in array – using index position 8

PS C:\> $array[0]
22
Last item in array – using index position
PS C:\> $array[-1]
8

441
Example: Determine the number of items in an array
Determine PS C:\> $array.Count
number of 7
items in
array PS C:\> $array.Length
7

442
Module 13: Arrays

Section 2: Using Arrays Lesson 3: Adding Array Items

Microsoft Confidential 443


Example: Adding items to an array
Adding PS C:\> $array += 999
items to an
array PS C:\> $array
22
5
10
8
12
9
8
999

444
Module 13: Arrays

Section 2: Using Arrays Lesson 4: Sorting Arrays

Microsoft Confidential 445


Example: Sort-Object only sorts the console output – Array order is not changed
Sorting PS C:\> $array | Sort-Object –Descending
Array 999
Display 22
12
10
9
8
8
5

446
Example: Array Type Static Method Sort changes item order
Sorting PS C:\> [array]::Sort($myarray)
Array PS C:\> $myarray
5
8
8
9
10
12
22
999

447
Module 13: Arrays

Section 2: Using Arrays Lesson 5: Modifying Array Items

Microsoft Confidential 448


Example: Manipulating items in an array – Manipulating items in an array –
Manipulating Using assignment operator Using array method
items in an PS C:\> $array[0] = 100 PS C:\> $array.Set(0,200)
array
PS C:\> $array PS C:\> $array
100 200
8 8
8 8
9 9
10 10
12 12
22 22
999 999

449
Module 13: Arrays

Section 2: Using Arrays Lesson 6: Determine Array Object


Members

Microsoft Confidential 450


Piping to Get-Member discovers item members – Not array members
Example:
Determine PS C:\> $array | Get-Member
TypeName: System.Int32
array object
members Name MemberType Definition
---- ---------- ----------
CompareTo Method int Compare

Use Get-Member –Inputobject parameter to get array members
PS C:\> Get-Member -InputObject $array
TypeName: System.Object[]

Name MemberType Definition


------- --------------- -----------
Count AliasProperty Count = Length
Add Method int

451
Module 13: Arrays

Lab

Microsoft Confidential 452


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 453


Module 14: Hash Tables

Module Overview

Microsoft Confidential 454


Module 14: Hash Tables

Section 1: Hash Table Introduction Section 2: Hash Table Use Cases


• What are Hash Tables? • Hash Table Examples
• Creating Hash Tables
• Accessing Hash Table Items Section 3: Ordered Dictionary
• Modifying Hash Table Items • Ordered Dictionary
• Sorting Hash Tables

Microsoft Confidential 455


Module 14: Hash Tables

Section 1: Hash Table Lesson 1: What are Hash Tables


Introduction

Microsoft Confidential 456


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 457


Module 14: Hash Tables

Section 1: Hash Table Lesson 2: Creating Hash Tables


Introduction

Microsoft Confidential 458


Example: Empty hash table
Creating PS C:\> $hash = @{}
hash tables
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
Serial THX1138
Memory 68719476736

459
Create a hash table from here string data
Example:
Creating PS C:\> $string = @"
Msg1 = Hello
hash tables Msg2 = Enter an email alias
Msg3 = Enter an username
Msg4 = Enter a domain name
"@

PS C:\> ConvertFrom-StringData -StringData $string

Name Value
---- -----
Msg4 Enter a domain name
Msg3 Enter an username
Msg2 Enter an email alias
Msg1 Hello

460
Create a hash table of services using Group-Object -AsHashTable
Example:
PS C:\> $svcshash = Get-Service |
Creating
Group-Object Status -AsHashTable -AsString
hash tables
PS C:\> $svcshash

Name Value
---- -----
Stopped {AeLookupSvc, ALG, AppMgmt, AppReadiness...}
Running {AppIDSvc, Appinfo, AudioEndpointBuilder,...}

PS C:\> $svcshash.Stopped

Status Name DisplayName


------ ---- -----------
Stopped AeLookupSvc Application Experience
...
461
Module 14: Hash Tables

Section 1: Hash Table Lesson 3: Accessing Hash Table


Introduction Items

Microsoft Confidential 462


Display all items in hash table
PS C:\> $Server

Example: Name Value


Access ---- -----
HV-SRV-1 192.168.1.1
hash tables Serial THX1138
items Memory 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
463
Example: Display all keys in hash table
Display all PS C:\> $Server.Keys
hash tables HV-SRV-1
keys Serial
Memory

464
Example: Display all values in hash table
Display all PS C:\> $Server.Values
hash tables 192.168.1.1
values THX1138
68719476736

465
Module 14: Hash Tables

Section 1: Hash Table Lesson 4: Modifying Hash Table


Introduction Items

Microsoft Confidential 466


Add or set key and value using index notation
PS C:\> $Server["CPUCores"] = 4
Example:
Manipulate
hash table Add or set key and value using dot notation
items 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 Lesson 5: Sorting Hash Tables


Introduction

Microsoft Confidential 468


Example: • Hash tables are intrinsically unordered
Sorting • It is not possible to sort a hash table
hash tables • GetEnumerator() method used with Sort-Object Cmdlet

Sort hash table display by key


PS C:\> $Server.GetEnumerator() | Sort-Object -Property key

Name Value
---- -----
CPUCores 4
Drives {C, D, E}
HV-SRV-1 192.168.1.1
Memory 68719476736
Serial THX1138

469
Module 14: Hash Tables

Section 1: Hash Table Lesson 6: Searching Hash Tables


Introduction

Microsoft Confidential 470


Searching a hash table
Example:
Searching PS C:\> $hash = @{"John"=23342;"Linda"=54345;"James"=65467}
hash tables PS C:\> $hash.ContainsKey("Linda") # Fast hashed key search
True

PS C:\> $hash.ContainsValue(19) # Slow non-hashed search


False

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

471
Module 14: Hash Tables

Section 2: Hash Table Use Cases Lesson 1: Hash Table Examples

Microsoft Confidential 472


• 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,
Example: @{Name="Size (KB)";Expression={"{0:N2}" -f ($_.Length/1Kb)}}
Calculated
Property
Name Size (KB)
---- ---------
HelpPane.exe 950.50
un_dext.exe 94.91

Key Value Key Value

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

Hash
Table
473
Example: Passing a hash table as parameters to a cmdlet, function or script
Splatting Referred to as ‘Splatting’
\$params = @{
LogName = "application"
Newest = 10
EntryType = "Warning"
ComputerName = "localhost"
}

Get-EventLog @Params

474
Example: Create a customized object (PS v2.0+) – Ordering Not Preserved
Custom
$props = @{
PSObject 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

475
Example: Create a customized object (PS v3.0+) – Ordering Preserved
Custom
$newobj = [PSCustomObject]@{
PSObject 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
}

476
Module 14: Hash Tables

Section 3: Ordered Dictionary Lesson 1: Ordered Dictionary

Microsoft Confidential 477


Ordered Dictionary

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


regular hash Name Value
tables ---- ----- Order not
preserved
• Works similarly lastname Smith
firstname John
to a hash table
but order is PS C:\> [ordered]@{firstname = "John" ; lastname = "Smith"}
preserved
Name Value
---- -----
firstname John Insertion order
lastname Smith preserved

Microsoft Confidential 478


Module 14: Hash Tables

Lab

Microsoft Confidential 479


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 480


Module 15: Flow Control

Module Overview

Microsoft Confidential 481


Module 15: Flow Control
Section 1: Looping • SWITCH Statement - Multiple Inputs
• The Five Loops • SWITCH Statement - Case
• While • SWITCH Statement - Wildcard
• Do While • SWITCH Statement - Regex
• Do Until • SWITCH Statement - Expression Match
• For • SWITCH Statement - File Processing
• ForEach • IF and SWITCH Statement Difference

Section 2: Branching Section 3: Flow Control Keywords


• IF Statement • Flow Control Keywords
• Basic SWITCH Statement
• SWITCH Statement - Default Condition

Microsoft Confidential 482


Module 15: Flow Control

Section 1: Looping Lesson 1: The Five Loops

Microsoft Confidential 483


PowerShell’s 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 Enumeration Runs code once for each item in collection/array
Choose automatic variable name
Microsoft Confidential 484
Module 15: Flow Control

Section 1: Looping Lesson 2: While

Microsoft Confidential 485


While Loop

Name Description Example


While Runs script block while $a = 0
conditional test = true While ($a –lt 10) {$a; $a++}

Is Yes
Start Condition Run Code
True?

No

End

Microsoft Confidential 486


Example: $ComputerName = '2012R2-DC'

While 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 Restart-Computer


introduced the –Wait parameter

Microsoft Confidential 487


Module 15: Flow Control

Section 1: Looping Lesson 3: Do While

Microsoft Confidential 489


Do While Loop
Name Description Example
Do Condition evaluated AFTER script block runs at $a = 0
While least once Do {$a; $a++} While ($a -le 5)

Runs script block if conditional test = true

Yes

Is
Start Run Code Condition
True?

No

End

Microsoft Confidential 490


Example: $ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Do While
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 Restart-Computer


introduced the –Wait parameter

Microsoft Confidential 491


Module 15: Flow Control

Section 1: Looping Lesson 4: Do Until

Microsoft Confidential 492


Do Until Loop
Name Description Example
Do Condition evaluated AFTER script block Do {$a; $a++} Until ($a –gt 10)
Until runs at least once

Runs script block if conditional test = false

No

Is
Start Run Code Condition
True?

Yes

End

Microsoft Confidential 493


Example: $ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Do Until
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 Restart-Computer


introduced the –Wait parameter

Microsoft Confidential 494


Module 15: Flow Control

Section 1: Looping Lesson 5: For

Microsoft Confidential 495


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}

Is Yes
Start Initialise Condition Run Code Increment
True?

No

End

Microsoft Confidential 496


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 497


Module 15: Flow Control

Section 1: Looping Lesson 6: ForEach

Microsoft Confidential 499


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}

Yes Set Value of $<item> to


Items in
Start current array/collection Run Code
Array?
element

No

End

Microsoft Confidential 500


Example: $Services = Get-Service
'There are a total of ' + $Services.Count + ' services.'
ForEach ForEach ($Service in $Services)
Loop {
$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 502


Module 15: Flow Control

Section 2: Branching Lesson 1: IF Statement

Microsoft Confidential 503


IF Statement

Branching structure
chooses which code to run If (<test1>) {<statement list 1>}

Optional – Elseif(s) used for [ElseIf (<test2>) {<statement list 2>}]


additional test(s)
[ElseIf (<test3>) {<statement list 3>}] Optional

Optional – Else code runs if [Else {<statement list 4>}]


test(s) fail

Only one code block will


run

Microsoft Confidential 504


If
Start

Is Yes
If (<test1>) condition Run Statement List 1
{ True?
<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 505


Start
If..Else
If (<test1>) Is Yes
{ condition Run Statement List 1
<statement list 1> True?
}
No
Else
{ Run Else Statement List
<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 506
If..Elseif(s)
Start

If (<test1>) Is first Yes


{ condition Run Statement List 1
<statement list 1> True?
} No
ElseIf (<test2>)
{ Is second Yes
<statement list 2> condition Run Statement List 2
} True?
ElseIf (<test3>) No
{
<statement list 3> No
Is third Yes
} condition Run Statement List 3
True?

No

End

Microsoft Confidential 507


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 508


If..ElseIf(s)..Else
Start

If (<test1>) Is first
{ Yes
condition Run Statement List 1
<statement list 1> True?
}
ElseIf (<test2>) No
{
<statement list 2> Is second Yes
} condition Run Statement List 2
Else True?
{
No
<else statement list>
}
Run Else Statement

End

Microsoft Confidential 509


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
}

510
Module 15: Flow Control

Section 2: Branching Lesson 2: Basic SWITCH


Statement

Microsoft Confidential 514


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 515


Simple Switch Start

Switch (<test-value>)
{
<condition 1> {<action 1>}
<condition 2> {<action 2>} <test-value> True
-EQ Run <action 1>
} <condition 1>

False
$DomainRole = (Get-CimInstance -class
Win32_ComputerSystem).DomainRole
<test-value> True
switch ($DomainRole) -EQ Run <action 2>
<condition 2>
{
0 {write-Host "standalone workstation"}
2 {write-Host "standalone server"} False
}

End

Microsoft Confidential 516


Module 15: Flow Control

Section 2: Branching Lesson 3: SWITCH Statement


- Default Condition

Microsoft Confidential 521


Start
Switch – With Default Case
Switch (<test-value>)
<test-value> True
-EQ Run <action 1>
{ <condition 1>
<condition 1> {<action 1>}
<condition 2> {<action 2>}
Default {<action 3>} False
}
<test-value> True
-EQ Run <action 2>
<condition 2>
$DomainRole = (Get-CimInstance -class
Win32_ComputerSystem).DomainRole
False
switch ($DomainRole)
{
0 {write-Host "standalone workstation"} No Conditions
True
2 {write-Host "standalone server"} Matched? Run <action 3>
Default {write-Host "other domain role"}
}
False

End
Microsoft Confidential 522
Module 15: Flow Control

Section 2: Branching Lesson 4: SWITCH Statement


– Multiple inputs

Microsoft Confidential 525


Switch Start Process Value

Multiple Values
Switch (<test-value-array>) <test-value> True
{ -EQ Run <action 1>
<condition 1> {<action 1>} <condition 1>
Default {<action 2>}
} False

True
$FileNames = (Get-ChildItem C:\Windows).FullName No Conditions
Switch -Wildcard ($FileNames) Matched? Run <action 2>
{
"*.exe" {"Found executable: $_"}
Default {"Not an exe: $_"} False
}

False True
End False Additional
Values?

Microsoft Confidential 526


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

527
Example: PS C:\> switch (123,200)
SWITCH {
Multiple 123 {Write-Host $_ -ForegroundColor Green}
inputs 200 {Write-Host $_ -ForegroundColor Cyan}
}

123
200

528
Module 15: Flow Control

Section 2: Branching Lesson 5: SWITCH Statement


– Case

Microsoft Confidential 529


Example:
SWITCH

Case-insensitive by default

switch ("HELLO")
{
"hello" {"lowercase"}
"HELLO" {"uppercase"}
}

lowercase
uppercase

530
Example:
SWITCH
Case Sensitive

switch -CaseSensitive ("HELLO")


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

uppercase

531
Module 15: Flow Control

Section 2: Branching Lesson 6: SWITCH Statement


– Wildcard

Microsoft Confidential 532


Example:
SWITCH
without
-Wildcard

Switch (Get-ChildItem -Path c:\)


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

Windows

533
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

534
Module 15: Flow Control

Section 2: Branching Lesson 7: SWITCH Statement


– Regex

Microsoft Confidential 535


switch –Regex (Get-ChildItem -Path c:\)
{
"^program" {Write-Host $_ -ForegroundColor Green}
"s$" {Write-Host $_ -ForegroundColor Cyan}
Example:
}
SWITCH with
-Regex Program Files
Program Files
Program Files (x86)
Scripts
Users
Windows

^ Matches beginning character(s)


Note

$ Matches end character(s)


Get-Help about_Regular_Expressions
536
Module 15: Flow Control

Section 2: Branching Lesson 8: SWITCH Statement –


Expression Match

Microsoft Confidential 537


Example: PS C:\> switch (123) {
SWITCH
Expression {$_ -lt 124} {Write-Host $_ -ForegroundColor Green}
matches {$_ -gt 200} {Write-Host $_ -ForegroundColor Cyan}

123

538
Module 15: Flow Control

Section 2: Branching Lesson 9: SWITCH Statement –


File Processing

Microsoft Confidential 539


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

540
Module 15: Flow Control

Section 2: Branching Lesson 10: IF and SWITCH


Statement Difference

Microsoft Confidential 541


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 542


Module 15: Flow Control

Section 3: Flow Control Keywords Lesson 1: Flow Control Keywords

Microsoft Confidential 543


Flow Control Keywords
Keyword Description Example(s)
Break Immediately Switch –Wildcard ("WMF 5.0")
exit Loop {
"WMF 5.0" {"Matched First"; Break}
Example "W*" {"Matched Second"}
breaks after 1 }
match to avoid
multiple Matched First
matches
Continue Immediately $c = 0
returns to top While ($c -lt 3)
of loop {
$c++
Example skips if ($c -eq 2) {Continue}
over 2 Write-Host $c
}
1
3 Microsoft Confidential 544
Flow Control Keywords
Keyword Description Example(s)
Return Exits current ‘scope’, function Test-Return ($val)
which can be a function, {
script, or script block if ($val -ge 5) {return $val}
Write-Host "Reached end of function"
Note: Return can appear }
alone or followed by a PS C:\> Test-Return 1
value or expression Reached end of function
PS C:\> Test-Return 6
6
Exit Exit current script or PS C:\> Exit 10
session – Optional
ErrorLevel Numeric
Code

Note: ‘Scopes’ are covered in a subsequent module


Microsoft Confidential 545
Example:
Exit and
ErrorLevel from
Cmd prompt

Microsoft Confidential 546


Module 15: Flow Control

Lab

Microsoft Confidential 547


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 548


Module 16: Scope

Module Overview

Microsoft Confidential 549


Module 16: Scopes
Section 1: Scope Introduction Section 3: Dot Source Notation
• What are Scopes? • Dot Source Notation

Section 2: Scope Modifiers Section 4: Profiles


• Using Scope Modifiers • Profiles

Microsoft Confidential 550


Module 16: Scope

Section 1: Scope Introduction Lesson 1: What are Scopes?

Microsoft Confidential 551


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 552


Scope determines lifetime & visibility of:

Variables

Functions

Aliases

PSDrives

Microsoft Confidential 553


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 554


Example: Scopes
Global Scope Lifetime
Items cease to exist when
the scope terminates
PS C:\> $Servername = 'Server01'
PS C:\> $Servername
Server01 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 Function Scope


Server01

Visibility
Child scopes have access
to Parent scope items

556
Module 16: Scope

Section 2: Scope Modifiers Lesson 1: Using Scope Modifiers

Microsoft Confidential 557


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 558


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 559


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 560


Example: List variables in local scope
List items PS C:\> Get-Variable -Scope Script

in a
scope
List PSDrives in local scope
PS C:\> Get-PSDrive -Scope Local

List aliases in global scope


PS C:\> Get-Alias -Scope Global

561
Module 16: Scope

Section 3: Dot Source Notation Lesson 1: Dot Source Notation

Microsoft Confidential 562


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 563


Example: Dot Source Script
Dot PS C:\> . C:\Scripts\FunctionExample.ps1
Source
Notation
Scripts

Notice space between


dot and path

564
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@
565
Module 16: Scope

Section 4: Profiles Lesson 1: Profiles

Microsoft Confidential 567


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 568


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
Profile 4 - Current User, Current Host
priority

PS:/>

Microsoft Confidential 569


$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 Name
Current User, Current Host $Profile or $Profile.CurrentUserCurrentHost
Current User, All Hosts $Profile.CurrentUserAllHosts
All Users, Current Host $Profile.AllUsersCurrentHost
All Users, All Hosts $Profile.AllUsersAllHosts

Microsoft Confidential 570


Profile Paths Common to ISE and Console

Scope Name
Current User,
$Home\Documents\WindowsPowerShell\profile.ps1
All Hosts
All Users,
$PsHome\profile.ps1
All Hosts

Microsoft Confidential 571


ISE Only Profile Paths

Scope Name
Current User,
$Home\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
Current Host
All Users,
$PsHome\Microsoft.PowerShellISE_profile.ps1
Current Host

Note “ISE” in the filename

Microsoft Confidential 572


Console Only Profile Paths

Scope Name
Current User,
$Home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Current Host
All Users,
$PsHome\Microsoft.PowerShell_profile.ps1
Current Host

Note no “ISE” in the filename

Microsoft Confidential 573


Example:
Listing
Profile Paths

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

AllUsersAllHosts : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
AllUsersCurrentHost : 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

574
Script Libraries in Profiles
• The profile script contents are automatically “dot-sourced”
• Scripts called from profile might need to be “dot-sourced”
• 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 575


Module 16: Scope

Lab

Microsoft Confidential 576


Agenda
Module 1: Introduction Module 10: Providers
Module 2: Commands 1 Module 11: Variables & Data Types
Module 3: Pipeline 1 Module 12: Operators 2
Module 4: Commands 2 Module 13: Arrays
Module 5: Scripts Module 14: Hash Tables
Module 6: Help System Module 15: Flow Control
Module 7: Object Models Module 16: Scope
Module 8: Operators 1 Module 17: Modules
Module 9: Pipeline 2

Microsoft Confidential 577


Module 17: Modules

Module Overview

Microsoft Confidential 578


Module 17: Modules
Section 1: Module Introduction Section 2: Script Module
• What are Modules? • Creating a Script Module
• Module Types • Module Manifest
• Cmdlets for Module Management
• Module Loading Section 3: Module Scope
• Module Scope

Microsoft Confidential 579


Module 17: Modules

Section 1: Module Introduction Lesson 1: What are Modules?

Microsoft Confidential 580


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 581


Core Modules
PowerShell v4 only ships with core Module Name
Microsoft.PowerShell.Core
modules
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Many administrative cmdlets and functions
Microsoft.PowerShell.Management
come from modules provided with Microsoft.PowerShell.Security
Windows and applications Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
Windows 8, 8.1, Server 2012 and Server ISE
2012R2 include dozens of modules and PSDesiredStateConfiguration
thousands of commands PSScheduledJob
PSWorkflow
PSWorkflowUtility

Microsoft Confidential 582


Module 17: Modules

Section 1: Module Introduction Lesson 2: Module Types

Microsoft Confidential 583


Module Types

Module Code

Binary Script Dynamic


Module Module
Module
(.dll) (.psm1)

Exists only in memory,


Typically compiled Typically scripted created on-the-fly
cmdlets and providers functions
Holds proxy functions for
implicit remoting
Optional Module Manifest

Module Manifests (.psd1) contain metadata


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

Microsoft Confidential 584


Module 17: Modules

Section 1: Module Introduction Lesson 3: Cmdlets for Module


Management

Microsoft Confidential 585


Get-Module – Imported Modules

List imported modules


PS C:\> Get-Module

ModuleType Version Name ExportedCommands


---------- ------- ---- ----------------
Script 1.0.0.0 ISE {Get-IseSnipp...
Manifest 3.1.0.0 Microsoft.PowerShell.Ma... {Add-Computer...
Manifest 3.1.0.0 Microsoft.PowerShell.Ut... {Add-Member, ...

Microsoft Confidential 586


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


Locations
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 0.0 TestModule {Say-Hello, Say-Goodbye}

Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version Name ExportedCommands


---------- ------- ---- ----------------
Manifest 1.0.0.0 ActiveDirectory {Add-ADCentralAccessPolicyMem...
Manifest 1.0.0.0 AppBackgroundTask {Disable-AppBackgroundTaskDia...
... Microsoft Confidential 587
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 588


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 589


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 590


Module 17: Modules

Section 1: Module Introduction Lesson 4: Module Loading

Microsoft Confidential 591


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 592


Example: List module path folders
List PS C:\> $env:PSModulePath -split ';'
PS v2.0+
module C:\Users\John\Documents\WindowsPowerShell\Modules
Default

path C:\windows\system32\WindowsPowerShell\v1.0\Modules
C:\Program Files\WindowsPowerShell\Modules
folders

PS v4.0+ Default

593
Command Discovery

Get-Command (v3.0+) will return commands from imported and available modules

Get-Command

Loaded Commands Commands in Available Modules


(Get-Module) (Get-Module –ListAvailable)

Microsoft Confidential 594


Get name of snap-in or module from which a cmdlet originates
PS C:\> (Get-Command Get-Date).ModuleName
Example: Microsoft.PowerShell.Utility
Get commands in PSScheduledJob module
Get-
Command PS C:\> Get-Command -Module PSScheduledJob

Support for CommandType Name ModuleName


Modules ----------- ---- ----------
Cmdlet Add-JobTrigger PSScheduledJob
...
Get only commands in current session
PS C:\> Get-Command -ListImported

CommandType Name ModuleName


----------- ---- ----------
Function A:
...
595
Module 17: Modules

Section 2: Script Module Lesson 1: Creating a Script


Module

Microsoft Confidential 596


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 for use in PowerShell session
Import Script as Module

Create Module Script


1. Import-Module c:\MyModule.psm1
MyModule.psm1
Function Get-Data
or
{
“Simple function” 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
Export-ModuleMember
If a script module does not include Export-ModuleMember,
functions are exported but not variables or aliases

Can only be used in script modules or dynamic modules

Optional but best practice

Explicitly define items to


be imported when
module is loaded

Microsoft Confidential 598


Module 17: Modules

Section 2: Script Module Lesson 2: Module Manifest

Microsoft Confidential 599


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-8234-bcdd9323c82d'
...

Microsoft Confidential 600


Module 17: Modules

Section 3: Module Scope Lesson 1: Module Scope

Microsoft Confidential 601


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 602


Module 17: Modules

Lab

Microsoft Confidential 603


Appendix: PowerShell Best
Practices

Microsoft Confidential 604


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

Errors
• Ensure you have error handling in place
• Use try{} catch{} finally{} blocks rather than $errorActionPreference
• Never have a single empty catch-block
Windows PowerShell v4.0 for
the IT Professional
Part 1

THANK YOU
Microsoft Confidential 608

You might also like