Professional Documents
Culture Documents
0 for the IT
Professional
Part 1
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
Break: 10:30 am
Lunch: 12:30 pm
Break: 2:45 pm
End: 5:00 pm
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
DAY 4
Module 8: Operators 1 Module 16: Scope
Module 17: Modules
Microsoft Confidential
2012R2-DC 2012R2-MS WIN8-WS
Environment Core
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.
Microsoft Confidential 9
Module 1: Introduction
Module Overview
Microsoft Confidential 10
Module 1: Introduction
Section 1: Shell
• What is a Shell?
• PowerShell Introduction
Microsoft Confidential 11
Module 1: Introduction
Microsoft Confidential 12
What is a Shell?
Reusable
Software enabling OS Utilities
Kernel
Hardware
Microsoft Confidential 13
What is PowerShell?
Microsoft Confidential 15
PowerShell Evolution
3.0 4.0
Code Name: 1.0 2.0
Monad
2005 2006 2008 2012 2013
Microsoft Confidential 16
PowerShell default availability
• 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 7 SP1
• Windows Server
2008 R2 SP1
OS
• Windows 8.1
• Windows Server
4.0 2012 or 2012 R2
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
Microsoft Confidential 20
Module 1: Introduction
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
Taskbar Tile
Microsoft Confidential 23
Module 1: Introduction
Microsoft Confidential 24
Scripting Language
Interactive Commands batched together:
Microsoft Confidential 25
Module 1: Introduction
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
Microsoft Confidential 28
Extended PowerShell Features
Covered in Windows PowerShell 4.0 for the IT Professional - Part 2
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
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
Microsoft Confidential 51
Module 2: Commands 1
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
Microsoft Confidential 54
What is a Cmdlet?
Verb-Noun
Single purpose
naming
Native PowerShell
Cmdlet Parameters to
control Cmdlet
command behaviour
Microsoft Confidential 55
Anatomy of a Cmdlet
Command Command
Name Parameters
Microsoft Confidential 56
Cmdlet Examples
PS C:\> Get-Process
Syntax Sample
PS C:\> Get-Command –Name Add-Computer –Syntax
Microsoft Confidential 58
Syntax Legend
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
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
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
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
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
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
Microsoft Confidential 65
Cmdlet Syntax Diagram
Parameter Sets
PS C:\> Get-Command –Name Stop-Process –Syntax
• 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
Microsoft Confidential 67
Common Parameters
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:\>
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:\>
Microsoft Confidential 72
Risk Mitigation Parameters
-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
Microsoft Confidential 75
Termination Characters
Statement Termination
;
• Semi-colon can be used to execute more than one statement on a single line
Id : 4
Handles : 1308
CPU : 1213.59375
Name : System
Microsoft Confidential 77
Line Continuation
Statement Termination
>>
• Still in the same statement
• Complete syntax and include an empty line to finish the statement and execute
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
Microsoft Confidential 80
Get-Command
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>]
...
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
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) ...
"[\\<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
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
Microsoft Confidential 97
Example: Full cmdlet name
Using built-in aliases PS C:\> Get-ChildItem C:\Windows
Microsoft Confidential 98
Module 2: Commands 1
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:\
Lab
Module Overview
External
command
PS C:\> whoami.exe
Contoso\administrator
Reads a text
file
Import-Csv Import-CliXml
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
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
InputObject SideIndicator
----------- -------------
Server3 =>
Output displayed in 2
columns by default
Output displayed in 3
columns
Export-Csv Export-CliXml
-NoTypeInformation
parameter avoids this as
1st line
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
Lab
Module Overview
Section 2: Functions
• Functions Introduction
Section 3: Remoting
• Introduction to PowerShell Remoting
• Using PowerShell Remoting
{<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
• Can be created with help topics that can be used with Get-Help (like cmdlets)
• Basic Syntax:
function <name>
{
param ($parameter1,$parameterN)
<statement list>
}
PS C:\> Get-ServiceInfo
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
Microsoft Confidential
Entry Point Transport Network
Resource-Specific
Cmdlets
Various Native OS Remoting
RPC
PowerShell WMI Cmdlets DCOM
Remote
Administration
Techniques CIM 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:\>
Interactive (1:1)
PS C:\>
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
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
Lab
Module Overview
• Can also:
• Be digitally signed for security
• Take parameter values
• Return values
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
Registry – Computer
• Affects all users on computer
• Stored in HKLM registry subkey (Admin access needed to change)
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
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
Directory: C:\Scripts
PS C:\scripts>
Microsoft Confidential 195
Module 5: Scripts
# Comment character
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
Qualify
Command #Create function with same name
Name PS C:\> Function Get-Process {"This isn't Get-Process"}
• 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
Ctrl-J
or
Edit -> Start Snippets
Microsoft Confidential 220
ISE Compiled Add-Ons
Lab
Module Overview
2
3
Internet Update-Help
• Only updates Help once per day even if run multiple times
o -Force can be used to update each time
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
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 –Module *
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
NAME
Get-SysLogNN
SYNOPSIS
Function that returns the most recent system event log entries.
SYNTAX
Get-SysLogNN [[-Log] <Object>] [[-NumberOfEvents] <Object>]
[<CommonParameters>]
...
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
Module Overview
• Structured Data
Steer Right
Colour
Wheelie
Size
$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"
• 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)
Example:
IntelliSense Object
Members
Property
Method
Lab
Module Overview
Compare values
Case-Sensitive
Version
PS C:\> 10 -gt 20
False
PS C:\> 10 -gt 5
True
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)
Case-Sensitive
Version
\d - Digit
^ - Start of Text
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
Operator Description
-xor TRUE only when one of the statements is TRUE and the other is FALSE.
Directory: C:\windows\System32
Directory: C:\windows\System32
Lab
Module Overview
Hello Netlogon
Hello Netman
Hello netprofm
Hello NetTcpPortSharing
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}
Position 1 is -Process
Parameter
• 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
}
}
-ComputerName <String[]>
Required? false
Position? 1
Default value Local computer
Accept pipeline input? True (ByValue, ByPropertyName)
Accept wildcard characters? false
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
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
Lab
Module Overview
336
Provider Capabilities
Name Description
Exclude Items can be excluded from 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
Microsoft Confidential
Module 10: Providers
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)
340
Module 10: Providers
Name Example
True
Join-Path PS C:\> Join-Path -Path C: -ChildPath Temp –Resolve
C:\Temp
iexplore.exe
Name Example
Lab
Module Overview
• Not case-sensitive
• Kinds of variables:
o Automatic (built-in)
o User-defined
Microsoft Confidential 360
Module 11: Variables and Data
Types
Name Example
Can not be changed with “=“ (must use Set-Variable with -Force)
PS C:\> $svcs
Remember, in PowerShell:
• Everything is an OBJECT
• Each OBJECT has a TYPE
• Variables reference OBJECTS
372
Module 11: Variables and Data
Types
374
Module 11: Variables and Data
Types
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
'@ "@
377
Module 11: Variables and Data
Types
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
PS C:\> (1.6).GetType().FullName
System.Double
PS C:\> (1tb).GetType().FullName
System.Int64
PS C:\> $MyNumber.GetType().FullName
System.Int32
387
Static Members
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
Operator Example
-is PS C:\> (get-date) -is [DateTime]
True
-isNot PS C:\> (get-date) -isNot [DateTime]
False
Same Result
PS C:\> [datetime]"27/12/2013"
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
398
Module 11: Variables and Data
Types
• ASCII 96
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
--%
Lab
Module Overview
$integer = $integer + 1
All produce same result
$integer += 1
$integer++
Microsoft Confidential 413
Module 12: Operators 2
PS C:\> "First name is: {1} Last name is: {0}" -f $MyArray
First name is: John Last name is: Smith
Text-separated-with-dash
Forced Width
(negative-left justified, positive-right justified)
Text -separated
Format as percentage
Format as percentage
with 0 decimal points
Round number to 2
decimal places
3.14
Format as local
computer currency
Format DateTime
11:35:16
Lab
Module Overview
439
Module 13: Arrays
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
444
Module 13: Arrays
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
449
Module 13: Arrays
451
Module 13: Arrays
Lab
Module Overview
• Get-Help about_Hash_Tables
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
"@
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
PS C:\> $Server.Serial
THX1138
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
Remove key
PS C:\> $Server.Remove("HotFixCount")
Module 14: Hash Tables
Name Value
---- -----
CPUCores 4
Drives {C, D, E}
HV-SRV-1 192.168.1.1
Memory 68719476736
Serial THX1138
469
Module 14: Hash Tables
PS C:\> $hash.ContainsValue(65467)
True
471
Module 14: Hash Tables
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
475
Example: Create a customized object (PS v3.0+) – Ordering Preserved
Custom
$newobj = [PSCustomObject]@{
PSObject Computer = (Get-WmiObject -Class Win32_computersystem).Name
476
Module 14: Hash Tables
Lab
Module Overview
Is Yes
Start Condition Run Code
True?
No
End
PS C:\
Yes
Is
Start Run Code Condition
True?
No
End
PS C:\
No
Is
Start Run Code Condition
True?
Yes
End
PS C:\
Is Yes
Start Initialise Condition Run Code Increment
True?
No
End
Computer 1: 2012R2-DC
Computer 2: 2012R2-MS
No
End
Branching structure
chooses which code to run If (<test1>) {<statement list 1>}
Is Yes
If (<test1>) condition Run Statement List 1
{ True?
<statement list 1>
} No
End
No
End
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
510
Module 15: Flow Control
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
End
Microsoft Confidential 522
Module 15: Flow Control
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?
switch ($DomainRole)
{
1 {Write-Host "$_ : Member Workstation"}
2 {Write-Host "$_ : Standalone Server"}
}
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
Case-insensitive by default
switch ("HELLO")
{
"hello" {"lowercase"}
"HELLO" {"uppercase"}
}
lowercase
uppercase
530
Example:
SWITCH
Case Sensitive
uppercase
531
Module 15: Flow Control
Windows
533
Example:
SWITCH with
-Wildcard
Program Files
Program Files (x86)
Windows
534
Module 15: Flow Control
123
538
Module 15: Flow Control
server1 is in file
540
Module 15: Flow Control
Lab
Module Overview
Variables
Functions
Aliases
PSDrives
PS C:\> C:\script.ps1
Visibility
Child scopes have access
to Parent scope items
556
Module 16: Scope
[<scope-modifier>]:<name>
Example:
Change or create a variable in global scope from another scope
$global:a = "one"
Example:
Make a function visible in global scope from another scope
function global:Hello
{write-host "Hello, World"}
in a
scope
List PSDrives in local scope
PS C:\> Get-PSDrive -Scope Local
561
Module 16: Scope
Script or function runs in current scope and creates items in current scope
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
Start PowerShell
Execute Profile
Scripts
PS:/>
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
Scope Name
Current User,
$Home\Documents\WindowsPowerShell\profile.ps1
All Hosts
All Users,
$PsHome\profile.ps1
All Hosts
Scope Name
Current User,
$Home\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
Current Host
All Users,
$PsHome\Microsoft.PowerShellISE_profile.ps1
Current Host
Scope Name
Current User,
$Home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Current Host
All Users,
$PsHome\Microsoft.PowerShell_profile.ps1
Current Host
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
Lab
Module Overview
Modules can contain cmdlets, scripts, functions, variables, aliases, and other useful
items
Module Code
Directory: C:\Users\administrator\Documents\WindowsPowerShell\Modules
Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules
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
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
Microsoft Confidential
Export-ModuleMember
If a script module does not include Export-ModuleMember,
functions are exported but not variables or aliases
-Scope <String>
Imports the module only into the specified scope.
Lab
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