PSITP v4 Part2 v1.4
PSITP v4 Part2 v1.4
0 for the IT
Professional
Part 2
Meet your trainer
<Trainer Name>
<Position, Location>
<[email protected]>
<other links>
• Name
• Company Affiliation
• Title/Function/Area of Responsibility
• Product experience
Start: 9:00am
Break: As Needed
Break: As Needed
End: 5:00pm
Microsoft Confidential 5
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 8
Module 1: Review of Part 1
Concepts
Module Overview
Microsoft Confidential 9
Windows PowerShell Introduction
Task-based command-line shell and scripting language, built on the .NET framework,
designed especially for system administration
Helps IT professionals and power users control and automate the administration of the
Windows operating system and applications that run on Windows.
Microsoft Confidential 10
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
Command Command
Name Parameters
Microsoft Confidential 12
PowerShell Commands Cont.
Microsoft Confidential 13
PowerShell Commands Continued
{Get-Process}
function GetEveryProcess
{
Get-Process
}
Microsoft Confidential 14
PowerShell Remoting Basics
Allows running commands against remote machine(s)
Types of remoting:
• Temporary
Invoke-Command -ComputerName 2012R2-DC `
–Credential contoso\administrator `
-ScriptBlock {Get-Culture}
• Persistent
New-PSSession -ComputerName 2012R2-DC –OutVariable ps
Invoke-Command –Session $ps -ScriptBlock {Get-Culture}
• Interactive:
Enter-PSSession -ComputerName 2012R2-DC
Microsoft Confidential 15
PowerShell Pipeline
The pipeline is a chain of cmdlets that passes objects
Microsoft Confidential 17
Scripts
Scripts can be run in either the Windows PowerShell console, ISE or launched
externally from cmd.exe
Microsoft Confidential 18
Scripts (Continued)
The default execution policy restricts Windows PowerShell from running any scripts
• Restricted
• Unrestricted
• AllSigned
• RemoteSigned
• Bypass
Microsoft Confidential 19
Scripts (Continued)
Comments are extra annotation added purely for readability of script:
# single-line comment
<#
multi-line
comment
#>
Microsoft Confidential 21
Objects
The Get-Member cmdlet lists the type members of an object (properties and
methods)
Microsoft Confidential 22
Operators
Windows PowerShell provides operators for comparison and evaluation.
• Comparison (-eq, -ne, -contains,-like, -match, etc.) & case sensitive variants
• Logical (-and, -or, -not, -xor)
Microsoft Confidential 23
Operators continued
Arithmetic (+ , - , / ,* ,%)
Microsoft Confidential 24
Operators continued
Bitwise
-bAnd, -bOr, -bNot, -bXor, -shl, -shr
Drives allow providers to be accessed using classic naming C:, Cert:, Alias:
Microsoft Confidential 26
Variables and Data Types
Variables reference objects
Microsoft Confidential 27
Variables and Data Types
"Double quotes" define an expandable string, ‘Single quotes’ define a literal string
$Number = 98052
"Expandable String $Number" Expandable String 98052
'Literal String $Number' Literal String $Number
Microsoft Confidential 28
Variables and Data Types
Static members (methods & properties)
• Can be used without creating an instance of a type
[int]$var1 = 124
$var1 = "Fred"
Cannot convert value "Fred" to type "System.Int32".
Error: "Input string was not in a correct format."
Microsoft Confidential 29
Variables and Data Types
Type Operators:
• -is, -isnot : return True or False.
• -as : converts datatypes
"PSv4" -is [string]
"09/09/2014" -as [datetime]
Microsoft Confidential 31
Arrays
Sorting
• sort pipeline output
$array | Sort-Object –Descending
Microsoft Confidential 32
Agenda
Microsoft Confidential 33
Module 2: Remoting
Module Overview
Microsoft Confidential 34
Module 2: Remoting
Microsoft Confidential 35
Module 2: Remoting
Microsoft Confidential 36
What is PowerShell Remoting?
Run commands on one or more remote computers
Utilize a temporary or a persistent connection, referred to as a session
A session connects to a runspace on the remote machine
A runspace is an instance of the PowerShell automation engine
Remote runspace capabilities can be constrained
Introduced in Windows PowerShell 2.0 and then enhanced in later versions
PS C:\>
Interactive (1:1)
PS C:\>
Microsoft Confidential 37
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
Requirements
Initiating user must be a member of the Local Administrators group on the remote
computer
Microsoft Confidential 39
Enabling Remoting using a Cmdlet
First, launch PowerShell with the "Run as administrator" option, then type:
PS C:\> Enable-PSRemoting
Microsoft Confidential 40
Enabling Remoting using a GPO
WinRM Service Automatic Startup
Allow remote server management (create listeners)
Microsoft Confidential 41
Windows Remoting Defaults
• Remoting is enabled on all 2012+ Server editions – Standard, Datacenter & Core
• Windows Remote Management (WinRM) Service running
• WS-Management (WSMan) protocol has an HTTP listener configured
• Inbound firewall rule for port 5985 is enabled (WsMan default listener port)
Microsoft Confidential 42
Example: Interactive Session
[2012R2-DC] PS C:\>
Local Computer
PS C:\>
43
Example: Temporary Session
44
Example: Persistent Session
45
Module 2: Remoting
Microsoft Confidential 46
Implicit Remoting
"Feels" like a local session
command, but runs remotely
Microsoft Confidential 47
Example: Import-PSSession
Microsoft Confidential 49
Module 2: Remoting
Microsoft Confidential 50
Object Serialization
• During remoting, objects are transmitted from a remote to a local session
• Serialization and de-serialization process occurs
• Some fidelity is lost. Methods are lost for non-basic types
• Basic Types typically de-serialize fully
Microsoft Confidential 51
Object
Serialization Invoke-Command
XML
TypeName: Deserialized.System.ServiceProcess.ServiceController
...
CanPauseAndContinue Property System.Boolean {get;set;}
Microsoft Confidential 54
PSComputerName property
• During de-serialization, the PSComputerName property is added to all objects
• Identifies object source during One-to-Many remoting
Microsoft Confidential 56
Remoting on Public Networks
Remoting on public networks is a potential security risk
• PowerShell v2.0: Enable-PSRemoting fails if host is connected to a public network
• PowerShell v3.0+ on Client OS: use the –SkipNetworkProfileCheck parameter
• PowerShell v3.0+ on Server OS: Enable-PSRemoting sets private and domain networks unrestricted,
but public networks are limited to the local subnet
Microsoft Confidential 57
Module 2: Remoting
Microsoft Confidential 58
Disconnected Sessions
Microsoft Confidential 59
Disconnected Sessions Overview
Invoke-Command
-InDissconnectedSession
Get-PSSession
-ComputerName
Connect-PSSession
Receive-PSSession
NOTE: Another user can connect to PSSessions, but only if they can supply the credentials that were used to
create the initial session.
Microsoft Confidential 62
Session State
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 Session1 2012R2-MS Disconnected Microsoft.PowerShell None
Connection to
Broken
Runspace lost
Microsoft Confidential 64
Session Availability
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 Session1 2012R2-MS Disconnected Microsoft.PowerShell None
Availability
Runspace not available
Ability for Remote Runspace None
to Accept Commands (not connected)
Microsoft Confidential 65
Example: View Session State and Availability
PS C:\> Disconnect-PSSession 4
Microsoft Confidential 66
Example: Session State and Availability
Microsoft Confidential 67
Robust Sessions
PowerShell 2.0
• Network issues may cause a remote PSSession to enter a "Broken" or "Closed" state
PowerShell 3.0+
• Remote Sessions remain in a "Connected" state for up to 4 minutes
• Progress bar indicates reconnection attempts
• Local session becomes "Broken" after 4 minutes
• Remote session becomes available for connection from anywhere, as the original user
Microsoft Confidential 69
Disconnected Session Timeout
Disconnected sessions are maintained until removed or the Idle Timeout expires
• IdleTimeout property
• Default is 2 hours
Microsoft Confidential 71
$Using variable scope prefix
PowerShell 2.0
• Invoke-Command -Argumentlist parameter passes local variables to script blocks
• Script block required an embedded Param() statement
• Invoke-Command -ArgumentList arguments are bound by position
PowerShell 3.0+
• Implements a new variable scope prefix
• $Using:<local variable name>
• No Param() statement or -ArgumentList parameter required
Microsoft Confidential 72
Module 2: Remoting
Microsoft Confidential 73
Remote Module Discovery and Import
Microsoft Confidential 74
Example: Remote Module Import
Microsoft Confidential 76
Remoting Endpoints
Microsoft Confidential 77
Example: Viewing Remoting Endpoints
PS C:\> Get-PSSessionConfiguration
Name : microsoft.powershell
PSVersion
StartupScript
: 4.0
:
Default endpoint for remoting
RunAsUser :
Permission : BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed
Name : microsoft.powershell.workflow
PSVersion : 4.0
StartupScript :
RunAsUser : Used for remote workflows
Permission : BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed
Name : microsoft.powershell32
PSVersion : 4.0
StartupScript :
RunAsUser
Permission
:
32-bit remoting
: BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed
Name : microsoft.windows.servermanagerworkflows
PSVersion : 3.0
StartupScript :
RunAsUser :
Permission : NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed
Endpoint for Server Manager
Microsoft Confidential 78
Session Configuration Cmdlets
Session configuration management cmdlets:
Other Endpoint Cmdlets Purpose
Get/Set-PSSessionConfiguration View and edit registered endpoint(s)
Register/Unregister-PSSessionConfiguration Create new or remove endpoint(s)
Enable/Disable-PSSessionConfiguration Enable or disable registered endpoint(s)
New/Test-PSSessionConfigurationFile Create or test configuration file (for simplified setup)
Set-PSSessionConfiguration –RunAsCredential
• Endpoint can run in the context of another user
• Initial connection requires only a lower privileged, delegated account
Microsoft Confidential 80
Endpoint Connection Permissions
Microsoft Confidential 81
Overall Process for Constrained Endpoints
restricted.pssc
Create Session Configuration File
• New-PSSessionConfigurationFile -Path .\restricted.pssc -SessionType
RestrictedRemoteServer
Microsoft Confidential 83
Authentication Mechanisms
Authentication Type Description Default Default
Endpoint (server) Client
Basic Username and Password sent (should use HTTPS) Disabled Enabled
(SSL required)
Digest Authentication exchange between client and server Not Supported Enabled
with digest session key used
Negotiate Windows integrated auth, Kerberos (preferred) or Enabled Enabled
NTLM
Kerberos Mutual authentication requiring a domain Enabled Enabled
Client Certificate- x.509 certificates public/private key authentication with Disabled Enabled
Based internal or internet PKI trust model
CredSSP Security Support Provider that allows credential Disabled Disabled
delegation
Configurable locally or via GPO
Microsoft Confidential 84
TrustedHosts
Microsoft Confidential 85
Example: Replace or Set TrustedHosts
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client
Microsoft Confidential 86
Example: Append TrustedHosts
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client
Microsoft Confidential 87
Example: Alternate Credentials (password typed interactively)
2012R2-MS
PS C:\>
Microsoft Confidential 88
Example: Alternate Credentials - multiple uses (password typed interactively once)
Microsoft Confidential 89
Example: Alternate Credentials – Hardcoded Password (clear text)
2012R2-MS
Warning: Anyone who gains access to this script gets the username and password
Microsoft Confidential 90
Example: Alternate Credentials – Hardcoded Password (Encrypted String)
#Run this line once manually on computer and user where script will run
$Username = 'contoso\administrator'
$Cred = New-Object PSCredential -ArgumentList $Username,$SecurePassword
2012R2-MS
Microsoft Confidential 91
Example: Alternate Authentication
Microsoft Confidential 92
Module 2: Remoting
Microsoft Confidential 93
Example: First, Identify Certificate Thumbprint
Microsoft Confidential 94
Example: Second, Create Listener (Local or Remote)
#Example 2: Remotely connect to WSMAN and create new HTTPS Listener on target using target’s certificate
$CertThumbprint = '3138F8B8B4A948ADAB752DE7E355408234D59800'
Connect-WSMan -ComputerName 2012R2-DC
New-Item `
-ItemType Listener `
-Path WSMan:\2012r2-dc\Listener `
-Address * `
-Transport HTTPS `
-CertificateThumbPrint $CertThumbprint
WSManConfig: Microsoft.WSMan.Management\WSMan::2012r2-dc\Listener
Microsoft Confidential 95
Example: Second, Create Inbound Firewall Rule (Local or Remote)
Microsoft Confidential 96
PS C:\> Invoke-Command -ComputerName 2012R2-DC.contoso.com `
Example:
Use SSL -ScriptBlock {Get-Culture} -UseSSL
Listener/
Endpoint LCID Name DisplayName PSComputerName
---- ---- ----------- --------------
3081 en-AU English (Australia) 2012R2-DC.contoso.com
97
Module 2: Remoting
Microsoft Confidential 98
The 2nd Hop Problem
Enter-PSSession
PS C:\> -ComputerName 2012R2-MS
False
Microsoft Confidential
Credential Delegation
By default:
• Your credentials are used to authenticate to the first machine
• Your security principal is used on the first hop machine
• Your credentials can not be passed from the first hop machine to the second hop
machine, thus the second hop authentication fails
Creating a custom endpoint using RunAs can achieve second hop without credential
delegation
• Fresh credentials are required, but cannot use the logged-in user or integrated authentication
The same precautions you take before you type your password on your own machine,
must be used on computers that may delegate your credentials
When enabling on the client, designate specific targets (avoid using wildcard *)
Use the same naming format throughout (either: short name, FQDN or IP)
Invoke-Command `
-Authentication CredSSP `
-Credential contoso\administrator `
-ComputerName 2012R2-MS `
-ScriptBlock {Test-Path \\2012R2-DC\FileShare}
True
Lab
Module Overview
Section 2: Parameters
• Lesson 1: Static Parameters
• Lesson 2: Switch Parameters
• Lesson 3: Dynamic Parameters
Section 3: [CmdletBinding()]
• Lesson 1: Overview
• Lesson 2: Risk Mitigation
• Lesson 3: Arguments
Microsoft Confidential 110
Module 3: Advanced Functions 1
Reusable code
Can include help content for use with Get-Help (like cmdlets)
Function [Scope:]<name>
{
Param ($parameter1,$parameterN)
<statement list>
<statement list>
}
PS C:\> Get-ServiceInfo
Special help comment keywords can be used to write Get-Help topics for functions
NAME
Get-SysLogNN
SYNOPSIS
Function that returns the most recent system event log entries.
SYNTAX
Get-SysLogNN [[-log] <Object>] [[-numberofevents] <Object>]
[<CommonParameters>]
...
Parameters may be defined within a Param() statement inside the function body.
Full set of advanced function parameter features are then available.
Syntax
function SwitchExample {
Param([switch]$state)
if ($state) {"on"} else {"off"}
}
PS C:\> SwitchExample
Off
Basic Syntax
function <name> {
Dynamicparam {<statement list>}
}
Microsoft Confidential 128
Example: Static
Dynamic Parameter
Parameter Determines
Slide 1/6 which other
Parameter(s)
will be
available
129
Example:
Dynamic Switch
Parameter Discovers
Slide 2/6 $param1 value
and creates
Dynamic
Parameters
accordingly
130
Example:
Dynamic
Parameter
Slide 3/6
Switch
If $param1 = val1 then Val1DP
parameter is available 131
Switch
If $param1 = val1 then Val1DP
parameter is available
Example:
Dynamic
Parameter
Slide 4/6
132
Example:
Dynamic
Parameter
Slide 5/6
Switch
If $param1 = val2 then Val2DP
parameter is available
133
Switch
If $param1 = val2 then Val2DP
parameter is available
Example:
Dynamic
Parameter
Slide 6/6
134
Module 3: Advanced Functions 1
Param() Required
$Args cannot be used
function <Name>
{
[CmdletBinding()]
Parentheses required even if Param ()
specifying no arguments }
function <Name>
{
[CmdletBinding(
SupportsShouldProcess=<Boolean>,
Optional arguments for the attribute ConfirmImpact=<String>,
DefaultParameterSetName=<String>,
are contained within the parentheses HelpURI=<URI>,
SupportsPaging=<Boolean>,
PositionalBinding=<Boolean>)]
Param ()
}
Surround the code that makes changes to the system with an If() statement
If ($pscmdlet.ShouldProcess("Target", "Operation"))
{
<Statement that makes changes>
}
$ConfirmPreference
• Automatic variable controls confirmation prompts
• Defaults to "High"
Function Kill-Process
{ [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="Medium
")]
Param([String]$Name)
Process
{
$TargetProcess = Get-Process -Name $Name
If ($pscmdlet.ShouldProcess($name, "Terminating Process"))
{
$TargetProcess.Kill()
}
}
}
Example: Changing to "High" will display
ShouldProcess confirmations
method
Function Kill-Process
{
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
Param([String]$Name)
Process
{
$TargetProcess = Get-Process -Name $Name
If ($pscmdlet.ShouldProcess($name, "Terminating Process"))
{
$TargetProcess.Kill()
}
}
}
Module 3: Advanced Functions 1
Lab
Module Overview
Optional
Parameter attribute has arguments that define the characteristics of the parameter
ParameterSetName
Specifies parameter set to which a
Param (
[parameter(ParameterSetName="Machine")] parameter belongs
[String[]]$MachineName,
[parameter(ParameterSetName="User")] If no parameter set is specified,
[String[]]$UserName parameter belongs to all the parameter
) sets defined by the function
Mandatory
Param ([parameter(Mandatory=$true)][String[]]
$MachineName)
Position
Param ([parameter(Position=0)][String[]]$MachineName)
ValueFromPipeline
Param ([parameter(ValueFromPipeline=$true)]
[String[]]$MachineName)
ValueFromPipelineByPropertyName
Param
([parameter(ValueFromPipelineByPropertyName=$true)]
[String[]]$MachineName)
Use if parameter
accepts property of an
object
ValueFromRemainingArguments
Param(
[parameter(ValueFromRemainingArguments=$true)] Parameter accepts all
[String[]]$ComputerName values that are not
) already assigned
function Print-Hello {
[OutputType([double])]
Param ($Name)"Hello $Name"
}
PS C:\> (Get-Command Print-Hello).OutputType
Name Type
---- ----
System.Double System.Double
Note: The OutputType attribute value is only a documentation note. It is not derived from the
function code, or compared to the actual function output. As such, the value may be inaccurate.
Below command displays the actual .NET type returned by the command
PS C:\> (Print-Hello -Name Johan).GetType().FullName
System.String
170
Module 4: Advanced Functions 2
IntelliSense suggests
allowed values
Lab
Module Overview
Section 1: Introduction
• Lesson 1: What is Regex?
• Lesson 2: Characters, Character Classes and Quantifiers
Enables parsing of large amounts of text to find specific character patterns, to validate,
extract, edit, replace, or delete text substrings
PS C:\> "Phone number: +61 42 911 1972" -match "\+\d{2} \d{2} \d{3} \
d{4}"
True
Note: Escape character for regular expressions ( \ ) is different than for PowerShell ( ` )
Statements
• Switch
[System.Text.RegularExpressions.Regex]
#type accelerator [regex]
[System.Text.RegularExpressions.RegexOptions]
[System.Configuration.RegexStringValidator]
PS C:\> $matches
Name Value
---- -----
0 Dev
192
Example: Groups continued
193
Mode Modifiers
Matching modes can be specified in the regex pattern
Specify regex options w/o using [System.Text.RegularExpressions.RegexOptions]
Useful with operators, where regex options cannot be specified
Can combine mode modifiers e.g. (?smi)
Use minus to turn mode off
197
Example 2: Search for match with switch –regex and extract data with $matches
function Get-WiFiSignalStrength {
$wlan = (netsh wlan show interfaces)
Switch -Regex ($wlan) {
"\d{2}%" {Write-Host $($matches.Values) -ForegroundColor Green}
}
}
\d Any decimal digit
{2} Exactly 2 matches
% Literal % sign
PS C:\> Get-WiFiSignalStrength
80%
198
Example 3: Replacing substrings with –replace or -creplace
PS C:\> "Mr. Henry Hunt, Mrs. Sara Samuels, Miss. Nicole Norris" `
-replace "Mr\. |Mrs\. |Ms\.",""
| Alternation operator
Mr. OR Mrs. OR Ms.
199
Example 4: Split text with –split or -csplit
200
Example 5: Split text with –split or -csplit
PS C:\> $a = @"
1The first line.
2The second line.
3The third of three lines.
"@
PS C:\> $a -split "^\d", 0, "multiline"
201
Example 6: Split text with regex TYPE
PS C:\> [Regex]::Split("www.microsoft.com","\.")
www
microsoft
Com
\. Matches a literal dot
[Regex] Built-in TYPE accelerator for [System.Text.RegularExpressions.Regex]
202
Example 7: Regex and regex option TYPES
203
Module 5: Regular
Expressions (Regex)
Lab
Module Overview
Runtime Errors
• When something goes wrong during code execution
• Only detectable when a specific state is reached or statement is
executed
Non-Terminating Errors
• Test for error and run handling code
• Can be converted into terminating error
• “Stop” with –ErrorAction or $ErrorActionPreference
• Use the "throw" keyword
Without separation, error and output objects would be mixed, requiring later filtering
2 – Error
• Execution Problems
• Shown by default in red
3 – Warning
• Less severe execution problems
• Shown by default in yellow
4 – Verbose
• More detailed execution information
• Hidden by default
5 – Debug
• Related to debugging code
• Hidden by default
PS C:\> $VerbosePreference
Cmdlet common parameters SilentlyContinue
• -Verbose, -Debug, -ErrorAction, -WarningAction
PS C:\> $DebugPreference
SilentlyContinue
No preference variable for Output Stream
• Controlled by assignments, redirection, and pipeline Preference levels covered with Error Action
$ErrorActionPreference
• Automatic variable for remaining script/function/session
PS C:\> $ErrorActionPreference
Continue
Automatic Variable
• Contains execution status of last operation
• Applies to both terminating and non-terminating errors
• Even applies to external command exit codes
Typically used in an If() statement, to test and then run error handling code
PS C:\> $?
False
PS C:\> $?
True
Ping request could not find host NotValidName. Please check the name and try again.
PS C:\> $?
False
Automatic variable – Array holds errors that have occurred in the current session
PS C:\> $MaximumErrorCount
256
Prevent an error from being added to the $Error array, by using "-ErrorAction Ignore"
PS C:\> $Error[0]
Write-Error "My Custom Error" : My Custom Error
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
Try/Catch/Finally
Encapsulate CODE into Try Block
Terminating error fires catch block
Finally block always run
even during Ctrl-C
Microsoft Confidential
Module 6: Error Handling
Useful in re-usable code to cause halt and report errors to caller for severe errors
If (1 -eq 1)
{
"Line before the terminating error"
Throw "This is my custom terminating error"
"Line after the throw" Line doesn’t run because
} of termination
PS C:\> C:\Simple-Throw-Sample.ps1
Line before the terminating error
This is my custom terminating error
At C:\Users\danpark\OneDrive @ Microsoft\Scripting\Simple-Throw-Sample.ps1:4
char:5
+ Throw "This is my custom terminating error"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (This is my custom terminating
error:String) [], RuntimeException
+ FullyQualifiedErrorId : This is my custom terminating error
PS C:\>
Function SampleThrowBasedMandatoryParam
{
Param ($ComputerName = $(Throw "You must specify a value"))
Get-CimInstance Win32_BIOS -ComputerName $ComputerName
}
PS C:\> SampleThrowBasedMandatoryParam
You must specify a value
At C:\Sample-Mand-Param-Throw.ps1:3 char:30
+ Param ($ComputerName = $(Throw "You must specify a value"))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (You must specify a value:String)
[], RuntimeException
+ FullyQualifiedErrorId : You must specify a value
SMBIOSBIOSVersion : 090006
Manufacturer : American Megatrends Inc.
Name : BIOS Date: 05/23/12 17:15:53 Ver: 09.00.06
SerialNumber : 7279-1135-6341-8380-3829-5634-16
Version : VRTUAL - 5001223
PSComputerName : 2012R2-MS
Useful for:
• Releasing resources
• Closing network connections
• Closing database connections
• Logging
• Etc.
Try
{
$wc = New-Object System.Net.WebClient
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc")
}
Catch [System.Net.WebException],[System.IO.IOException]
{
"Cannot get MyDoc.doc from http://www.contoso.com"
}
Catch
{
"An error occurred that could not be resolved."
$_.Exception.Message
}
Finally
{
If ($wc)
{
$_ contains caught error
$wc.Dispose()
}
}
Function function3 {
Try { NonsenseString }
Catch {"Error trapped inside function" ; Throw}
"Function3 was completed"
}
Try{ Function3 }
Catch { "Internal Function error re-thrown: $($_.ScriptStackTrace)" }
"Script Completed"
Microsoft Confidential 257
Module 6: Error Handling
Lab
Module Overview
Section 1: Introduction
• Lesson 1: Overview
• Lesson 2: Customized Debugging Information
The process of examining code while running to identify and correct errors
Windows PowerShell includes cmdlets to manage breakpoints and view the call stack
Custom Debug
Message
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"):
While paused, you can interact with the debug environment to:
• Examine variables
• Query runtime state
• Test conditions
Enabled
breakpoints
highlighted in
red
Hover over
Breakpoint
variable to see
Does not work for:
• $_ its value
• $input
• $PSBoundParameters
• $Args
Microsoft Confidential 278
Module 7: Debugging
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
[DBG]: PS C:\Scripts>> ?
PS C:\> . .\WF-TestSequence.ps1
PS C:\Scripts> test-seq
Hit Line breakpoint on 'C:\WF-TestSequence.ps1:3'
At C:\WF-TestSequence.ps1:3 char:9
+ sequence {
+ ~~~~~~~~~~
[WFDBG:localhost]: PS C:\>>
Enter-PSSession
At C:\ScriptEx.ps1:14 char:5
+ Get-EventLog -LogName $log -Newest $numberofevents
[2012R2-DC]: [DBG]: PS C:\>>
294
Debugging and Scope
Use Scope parameter of Get-Alias and Get-Variable to find variables and aliases
defined in script scope, e.g.:
Set-PSDebug -Trace 1
function Get-LogNN {
[CmdletBinding()]
Param ($log, $count)
Write-Debug "$(Get-Date -DisplayHint Time):Retrieving $count from $log"
Get-EventLog -LogName $log -Newest $count}
Get-LogNN -log system -count 2
PS C:\> .\fDebugEx.ps1
DEBUG: 7+ >>>> Get-LogNN -log system -count 2
DEBUG: 2+ function Get-LogNN >>>> {
DEBUG: 5+ >>>> Write-Debug "$(Get-Date -DisplayHint Time):Retrieving $count from
$log"
DEBUG: 5+ Write-Debug "$( >>>> Get-Date -DisplayHint Time):Retrieving $count from
$log"
DEBUG: 6+ >>>> Get-EventLog -LogName $log -Newest $count}
298
Debugging Cmdlets – Set-StrictMode
Set-StrictMode -Version • Affects only current scope and its child scopes
<1 or 2 or Latest>
• Specifies conditions that cause an error in strict mode
• Version determines level of enforced coding rules
function Get-LogNN {
Param ($log, $count)
Get-EventLog -LogName $log -Newest $count
Get-PSCallStack
}
Lab
Module Overview
Imperative
Add-WindowsFeature Windows-Server-Backup
Declarative
Configuration BaseBuild {
WindowsFeature Backup {
Ensure = "Present"
Name = "Windows-Server-Backup"
}
}
Microsoft Confidential
When to use DSC?
Automate configuration of a set of computers (target nodes)
Report Repair
Environment
Desired Desired Registry Scripts
Variables
State State
Option to create custom resources to configure the state of any application or system setting
DSC GPO
• No domain needed • Only works in domain scenario
• Works with no network at all • Connectivity generally needed
• MOF based (open platform) • Born from registry control
• Resources drive scalability • Fairly easy to setup and deploy
• Not as simple to deploy • Works everywhere
• Authentication flexibility • Well-known and established
• Requires PS v4.0
• Requires remoting is enabled
• New unknown factor
Microsoft Confidential
DSC Components
Configuration
Optional Pull
Resources
Server
DSC
Local
Configuration MOF Files
Manager
Microsoft Confidential
DSC Distribution Modes (Push vs. Pull)
Authoring Staging Nodes
Config Pushed
Server1
Config Pulled
Server1.mof Configs Deployed
Config Pulled
Server1.mof Configs Deployed
Server1.mof
File Share Server1
Microsoft Confidential 317
Module 8: Introduction to
Desired State Configuration
(DSC)
Defines the desired configuration and separates the configuration logic ("What") from
the node data ("Where")
Microsoft Confidential
Configuration Block Configuration CreatePullServer
The outside bounds {
param
(
[string[]]$ComputerName = 'localhost'
)
xDscWebService PSDSCPullServer
{
Ensure = "Present"
EndpointName = "PSDSCPullServer"
Microsoft Confidential
Port = 8080
Configuration CreatePullServer
{
param
Optional Param Block
(
[string[]]$ComputerName = 'localhost'
)
Node $ComputerName
{
WindowsFeature DSCServiceFeature
Valid Resource Name Cosmetic Name
{
Ensure = "Present"
Name = "DSC-Service"
}
xDscWebService PSDSCPullServer
{
Ensure = "Present"
Resource Properties EndpointName = "PSDSCPullServer"
Port Microsoft Confidential = 8080
Ensure = "Present"
EndpointName = "PSDSCComplianceServer"
Port = 9080
PhysicalPath = "$env:SystemDrive\inetpub\wwwroot\PSDSCC
CertificateThumbPrint = "AllowUnencryptedTraffic"
State = "Started"
IsComplianceServer = $true
DependsOn = ("[WindowsFeature]DSCServiceFeature","[x
}
}
}
Microsoft Confidential
Module 8: Introduction to
Desired State Configuration
(DSC)
Microsoft Confidential
Where to get resources
Download additional resources from Microsoft as Resource Kits hosted on the TechNet
Script Center
Microsoft Confidential
Built-in DSC Resources
Provider Description
Archive Unpacks archive (.zip) files at specific paths
Environment Manages system environment variables
File Manages files and directories
Group Manages local groups
Log Logs configuration messages
Package Installs and manages Windows Installer and setup.exe packages
Process Configures Windows processes
Registry Manages registry keys and values
Role Adds or removes Windows features and roles
Script Runs PowerShell script blocks
Service Manages services
User Manages local user accounts
Microsoft Confidential 327
Additional Resources
Microsoft Confidential
Create Custom Resources
Microsoft Confidential
*-TargetResource Functions
Microsoft Confidential
File Structure Overview
Microsoft Confidential
Module 8: Introduction to
Desired State Configuration
(DSC)
2. Execute Configuration
Microsoft Confidential
Managed Object Format
DSC Middle-Man
Per Node
In Pull Mode, node names
are abstracted with a GUID
Cross Platform
Microsoft Confidential
Module 8: Introduction to
Desired State Configuration
(DSC)
337
Microsoft Confidential
Module 8: Introduction to
Desired State Configuration
(DSC)
Run Configuration
to Create MOF
File(s)
Push
Configuration to
Target(s)
Microsoft Confidential
Single MOF
Configuration Pushed
Server1.mof
Server1
Microsoft Confidential
Many MOFs
Configuration Pushed
Server1.mof
Server1
Configuration Pushed
Server2.mof
Server2
Configuration Pushed
Server3.mof
Server3
Microsoft Confidential
Module 8: Introduction to
Desired State Configuration
(DSC)
Microsoft Confidential
Overview - Setting up for Pull
Authoring
Run Config ,
and Staging Create Pull
Create Config which creates
Server
MOF File(s)
Per Node
Targets Pull
Configure LCM
Config and
on targets
Apply
Microsoft Confidential
Resources and Clients
Push Configuration
• Resource manually deployed
Pull Configuration
• Pull server stores needed modules
• Pull client downloads modules based on configuration
Microsoft Confidential
Module 8: Introduction to
Desired State Configuration
(DSC)
Preparation:
Define Goals
Step 1:
Create Custom Resources (if required)
Step 2:
Define Configuration
Step 3:
Create consumable MOF File
Step 4:
Push Configuration to target node(s)
Directory: C:\MyWebConfig
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 10/02/2014 3:45 PM 1878 om12ms.mof
Lab
Module Overview
Section 1: Introduction
• Lesson 1: Overview
• Lesson 2: Authoring
• Lesson 3: Activities and Keywords
• Lesson 4: Workflow Execution
• Lesson 5: Checkpoints and Failure Recovery
An extensive product that spans many Microsoft products including Visual Studio and
the .NET Framework
Activities are authored in Visual Studio in native Windows Workflow Foundation (WF)
Extensible Application Markup Language (XAML) format
PowerShell Workflows reap all the benefits, but are authored in PowerShell script.
Parallelizable
• Easier to implement than background jobs or runspace pooling
Scalable
• Leverage the power of the Windows Workflow Foundation (WF)
Managed Node
In-Process
Workflow
Activity PowerShell
Host Remoting
Host
Managed Node
PowerShell
PowerShell
Workflow
Workflow Executive CIMOM/WMI
Cmdlets
PowerShell.exe
PowerShell
Activity Remoting
Host
PSJobProxy/
JobAPI/
PSRemoting
Managed Node
CIMOM/
WinRM WinRM PSWF Executive WMI
Client Service (wsmanprovhost.exe)
Function Workflow
Serial execution Parallel execution
Run to completion and return Can be paused, stopped and restarted
State is lost during an unexpected outage State is maintained, if requested, and is
recoverable after an unexpected outage
Run in the PowerShell Host engine context Run in the Windows Workflow engine context
Logging and recovery have to be implemented Logging and recovery are included
by the author
Commands, functions and cmdlets run in the Each activity executes in its own environment
same environment
Must be executed remotely using PowerShell Remote execution available using the
Remoting –PSComputerName workflow common parameter
Workflow Activities
Keyword Core Cmdlet / Workflow Script
Foreach Activity
Command Common
Inlinescript Parallel Sequence Common
Keyword Parameters –Parallel Parameters
Microsoft Confidential
Workflow Syntax
Uses the same syntax as a Windows PowerShell function
Supports common function parameters & CmdletBinding
Allows workflow common parameters to be specified
Workflow Syntax
workflow Test-Workflow
{
[CmdletBinding()]
Param([Parameter()]$Param1)
[<Activity>]
[<Activity>]
...
}
Important Parameters
• PSPersist - Force workflow to checkpoint workflow state and data after each activity
• PSComputerName - A list of computers to run workflow against
Process to Design a Workflow
Can the task be performed using simpler methods, such as Functions, Remoting or Jobs?
List Tasks to perform
Organize Tasks into Activities
Each activity should use a PowerShell cmdlet or custom function
376
Example: Multiple Activity Workflow
377
Core Cmdlet Activities
Core cmdlets have been packaged as workflow activities
• Some cmdlets have been excluded
• Microsoft.PowerShell.Core (PSSnapin)
• Microsoft.PowerShell.Host
Core Modules • Microsoft.PowerShell.Diagnostics
Containing Cmdlet • Microsoft.PowerShell.Management
• Microsoft.PowerShell.Security
Activities • Microsoft.PowerShell.Utility
• Microsoft.Wsman.Management
Activity
Common
Parameters
…
Example: Core cmdlet not packaged as a workflow activity
At line:1 char:20
+ workflow simplewf {Write-Host "Starting workflow..." -
ForegroundColor Green}
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cannot call the 'Write-Host' command. Other commands from this
module have been packaged as workflow activities, but this
command was specifically excluded. This is likely because the
command requires an interactive Windows PowerShell session, or
has behavior not suited for workflows. To run this command
anyway, place it within an inline-script (InlineScript
{ Write-Host }) where it will be invoked in isolation.
+ CategoryInfo : ParserError: (:) [],
ParseException
+ FullyQualifiedErrorId : CommandActivityExcluded
381
Workflow Activities and Keywords
ForEach –Parallel • Iterate through a collection and execute each item in parallel
Syntax
InlineScript
{
<Scriptblock>
} <ActivityCommonParameters>
Define a workflow that calls a .NET method – without using an InlineScript block
workflow DotNetMethod {
(Get-Service -Name BITS).Stop()
}
Parallel activity
Parallel
{
[<Activity>]
[<Activity>]
...
}
Sequence activity
Sequence
{
[<Activity1>]
[<Activity2>]
...
}
workflow test-seq {
parallel {
sequence {
Start-Process cmd.exe
Get-Process -Name cmd
} Script blocks
sequence { execute in parallel,
Start-Process notepad.exe individual activities
Get-Process -Name notepad
} execute in order
}
}
PS C:\> test-seq
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName PSComputer
Name
------- ------ ----- ----- ----- ------ -- ---------- ----------
27 3 1464 2292 12 0.00 9780 cmd localhost
95 8 1320 6608 104 0.03 16324 notepad localhost
Example 2: Multiple Activities with Parallel and Sequential Tasks
workflow Test-Workflow
{
Get-Service –Name Dhcp # workflow activity
Get-WindowsFeature –Name RSAT # Automatic InlineScript activity
Parallel
{
Sequence
{
Stop-Service -Name Dhcp
Start-Service -Name Dhcp
}
Sequence
{
Stop-Service -Name Bits
Start-Service -Name BITS
}
}
}
389
ForEach –Parallel Activity
Collection items can also be processed in Parallel
New-
New-
Check PSWorkflow Invoke-
Execute Suspend Resume PSWorkflow
Point Execution AsWorkflow
Session
Option
Microsoft Confidential
Execute a Workflow (In-Process)
396
Example : Initiating Workflow from PSv2.0+ on PSv3.0+ Workflow host
397
Module 9: Introduction to
Workflow
For more information about how to add checkpoints, see the help topics for Windows
PowerShell Workflow.
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName PSComputerName
------- ------ ----- ----- ----- ------ -- ----------- --------------
639 0 112 276 3 70.88 4 System 2012R2-MS
Example
Workflow Test-Workflow
{
Get-Process -Name wsmprovhost -PSPersist $True
}
If $True, checkpoint will be created after each activity (same as –PSPersist $True)
Example
Workflow Test-Workflow {
$WinRm = Get-Service Winrm
$PSPersistPreference = $true
$Assets = InlineScript {\\Server\Share\Get-Data.ps1}
...
$PSPersistPreference = $false
Parallel
{...}
Resume-Job will manually resume the workflow from the last checkpoint
Can create a scheduled job (on startup) to automatically resume suspended workflows
Example
workflow Test-Suspend {
$a = Get-Date
Suspend-Workflow
(Get-Date) - $a
}
Checkpoints on activities in a Parallel script block are not taken until Parallel script
block has run on all target computers
Checkpoints on activities in a Sequence script block, are taken after each activity
completes on the target computers
Lab
Pipeline
• Filter to the left, format to the right
• Accept input from the pipeline and send output to the pipeline
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
• Avoid single empty catch-blocks
Clickicon
Click icon to add
to add picture
picture Click icon to add p
Thank You
Microsoft Confidential 413
Appendix: PowerShell and
the Web
Module Overview
Perimeter Internal
Network Network
Internet
PowerShell
Web Access
Gateway
Server
Features
• Cross-platform access (tablets, smartphones, browsers)
• No extra cost or license
• Includes role configuration cmdlets
• Any browser with HTTPS, cookies and JavaScript enabled
• Save button in console allows disconnect/reconnect to an existing session without losing data
Requirements
• Windows Server 2012 (or later)
• IIS 8.0 Web Role
This example code is only appropriate for use in a test lab scenario. An unsecured, self-signed certificate is in use. The
PSWA authorization rule is set up without restrictions on users, computer destination, or session constraints. For a
production implementation far more security would be required.
Internet
Enterprise Firewall
PowerShell Web Access Gateway
IIS Authentication Client Certificate
PSWA Form Authentication
PSWA Authorization Rules
Firewall PowerShell Web Access Deployed on Internet
Returns HTTPWebResponseObject
Microsoft.PowerShell.Commands.HtmlWebResponseObject
List Methods
Name
----
Equals
GetHashCode
GetType
ToString
List Properties
PS C:\> $PSBlog | Get-Member -MemberType Properties | Format-Wide -Column 2
AllElements BaseResponse
Content Forms
Headers Images
InputFields Links
ParsedHtml RawContent
RawContentLength RawContentStream
Scripts StatusCode
StatusDescription
http://blogs.technet.com/b/josebda/archive/tags/hyper_2d00_v/
http://blogs.technet.com/b/wincat/archive/tags/virtualization/
http://blogs.technet.com/b/askcore/archive/tags/hyper_2d00_v/
http://blogs.technet.com/b/askcore/archive/tags/failover+cluster/
http://blogs.msdn.com/b/powershell/archive/tags/Advanced+Functions/
...
429
Invoke-RestMethod
title published
----- ---------
Now Available: System Center 2012 Service Pack 1 Update 2014-01-29 17:34:26
Service Management Automation and SharePoint - #MVP 2014-01-14 16:50:42
2014 and the year of the #LyncUp 2014-01-14 01:58:00
System Center Universe: US & Simulcast 2014-01-09 07:00:00
#MVA Course – ITIL for IT Pros 2013-12-10 15:21:11
Update Rollup 5 for System Center Advisor is available 2013-11-25 19:28:45
...
431
Example: Return titles and publish date from PowerShell Team blog
title pubDate
----- -------
ConvertFrom-String: Example-based text parsing Fri, 31 Oct 2014 19:36:35 GMT
Powershell DSC ResKit Wave 8: Now with 100+ Resources! Tue, 28 Oct 2014 20:41:00 GMT
Manage the PowerShell DSC Extension in the Azure Preview Portal Tue, 28 Oct 2014 17:52:00 GMT
PowerShell DSC Does Exchange! Tue, 21 Oct 2014 21:57:00 GMT
Heads Up: Hey, Scripting Guy! Blog Series Mon, 20 Oct 2014 18:33:00 GMT
Simple HTTP api for Executing PowerShell Scripts Mon, 29 Sep 2014 23:37:00 GMT
432
Appendix: Jobs
Module Overview
Start-Job:
Get-Job:
Receive-Job gets job results (or partial results if the job is incomplete)
CPU : 849.6282463
Wait-Job
• Suppresses the PowerShell prompt until the job is complete
Stop-Job
Get-Job –name n*| Stop-Job
Stop-Job *
Remove-Job
• The Job must be stopped before it can be removed
Child jobs created for each remote machine used with Invoke-Command
Use same job management cmdlets as local jobs once jobs exist
• Receive-Job, Remove-Job, Wait-Job, Stop-Job, etc.
• Scheduled jobs are a combination of PowerShell jobs and the Windows Task
Scheduler
• Jobs run asynchronously in the background
• Jobs include a rich job triggering mechanism
• Scheduled jobs can be run as a different user account
• The PSScheduledJob module includes 16 cmdlets
• Jobs can be managed using the *-Job cmdlets
Scheduled Jobs
Job Options Job Module
Define conditions for starting and PSScheduledJob module
running the job Only available in PowerShell 3.0
A Job Option reference is stored in Module must be loaded to manage
a job object property job instances using *-Job cmdlets
ScheduledJobDefinition
Options [ScheduledJobOptions]
JobTriggers <List>[ScheduledJobTrigger]
ScheduledJobTrigger
ScheduledJobOptions JobDefinition [ScheduledJobDefinition]
JobDefinition [ScheduledJobDefinition]
• Register-ScheduledJob • Get-ScheduledJob
• Unregister-ScheduledJob • Set-ScheduledJob
ScheduledJobDefinition
• Enable-ScheduledJob
• Disable-ScheduledJob
• New-ScheduledJobOption
ScheduledJobOption • Get-ScheduledJobOption
• Set-ScheduledJobOption
• Add-JobTrigger • Get-JobTrigger
• Remove-JobTrigger • Set-JobTrigger
ScheduledJobTrigger • Enable-JobTrigger
• Disable-JobTrigger
• New-JobTrigger
Microsoft Confidential 449
Create a Scheduled Job
PS C:\> Register-ScheduledJob -Name PSJob1 -ScriptBlock {dir
Example: c:\}
Creating Create Job Trigger Objects
New PS C:\> $trigger1 = New-JobTrigger -At (Get-
Scheduled Date).AddMinutes(10) –Once
Jobs & PS C:\> $trigger2 = New-JobTrigger -At 3pm -Weekly -
Triggers DaysOfWeek Monday
Associate a Job Trigger Object with a new or existing Scheduled Job
PS C:\> Register-ScheduledJob -Name PSJob2 –FilePath
$home\script.ps1 -Credential (Get-Credential) -Trigger
$trigger2
PS C:\> Add-JobTrigger -Name PSJob1 -Trigger $trigger1
450
PowerShell Scheduled Jobs in Task Scheduler
Id Name PSBeginTime
-- ---- -----------
4 TestJob5 29/10/2012 11:41:26 PM
5 TestJob5 29/10/2012 11:42:25 PM
Job output is saved to disk in an XML file –Keep is required to access results multiple times
Receiving Job Output
PS C:\> Receive-job -Id 6 –Keep
<Jobname>\
ScheduledJobDefinition.xml Output\
Results.xml Status.xml
Get-Job
Receive-Job –Job $myWfJob
Preparation:
Set Up Pull Server (if not already available)
Define Goals
Step 1:
Create Custom Resources (if required)
Step 2:
Create unique identifier (GUID)
Define Configuration
Step 3:
Create Consumable MOF File
Step 4:
Generate MOF File Checksum
Deploy configuration files to Pull Server
Step 5:
Configure Target Nodes
Microsoft Confidential 473
Preparation: Set up oData based Web Service DSC Pull Server
Note
• All resources in the DSC Resource Kit are provided AS IS, and are not supported through any Microsoft standard
support program or service
• DSC Resource Kit requires Windows 8.1 or Windows Server 2012 R2 with update KB2883200
7. Run DSC Configuration using F5 in the ISE to define it, then execute configuration to create a MOF file.
Note:
Use ‘nodename’ parameter, or run command locally on assigned Pull Server.
Command below defines a non SSL configuration. For SSL use a certificate in computer store of Pull
Server and specify its thumbprint.
PS C:\Scripts> Sample_xDscWebService `
–certificateThumbPrint "AllowUnencryptedTraffic" –OutputPath .
8. Apply the Configuration
Setting Value
Ensure that IIS is installed Yes
Define Web Server Name Web-Server
Define DestinationPath c:\inetpub\wwwroot
(Desired location to ensure state for a file or
directory)
Directory: C:\MyWebConfigPull
#...
instance of MSFT_DSCMetaConfiguration {
ConfigurationID = "66f08f93-155e-415f-ae11-702bff8ec6c8";
RefreshMode = "PULL";
DownloadManagerName = "WebDownloadManager";
RebootNodeIfNeeded = True; GUID from step 2
RefreshFrequencyMins = 15;
ConfigurationModeFrequencyMins = 15;
ConfigurationMode = "ApplyAndAutoCorrect";
DownloadManagerCustomData = {$keyvaluepair1,$keyvaluepair2};
};
instance of OMI_ConfigurationDocument {
Version = "1.0.0";
Author = "Johan";
};
Open Target Node Event Log: Applications and Services > Microsoft > Windows > Desired State Configuration
> Operational