SlideShare una empresa de Scribd logo
1 de 30
Intro to
PowerShell
Workflow
JEFF HICKS
Agenda
What is Workflow?
Workflow Syntax
Running Workflows
Practical Workflows
Best Practices
Think!
Just because you can use a PowerShell
workflow doesn’t mean you should.
Definitions – What is a
Workflow
A robust multi-machine orchestration
engine
Designed for long running unattended tasks
across potentially thousands of machines
Persistent states can survive reboots and
network interruptions
Previously built in Visual Studio
Definitions - What is
PowerShell Workflow?
• Persistence via check points
• Suspend and Resume capabilitiesRobust
• Parallel tasks
• Connection pooling
• Connection throttling
Performance
and
Scalability
• Use existing cmdlets*
• No need to master XAML or use Visual Studio
• Built in parameters for multi-machine management
PowerShell
Based
Workflow Scenarios
Server deployment
Server configuration/remediation
User provisioning
Private cloud deployments
Sharepoint configuration
Any business workflow that can be orchestrated with command line tools.
Key Workflow Concepts
Workflow is a series of orchestrated activities
Workflow activities are isolated
All data and objects are serialized
Objects are strongly typed
Workflows use static scoping
Requirements
Built on .NET Framework 4.0 and
Windows Workflow Foundation
Requires PowerShell 3.0
Requires PowerShell 3.0 remoting
Leverages PowerShell's job
infrastructure
Requirements: Remoting
Workflows connect to machines using WSMan protocol
Connects to the default Workflow session configuration
PS C:> get-pssessionconfiguration
microsoft.powerShell.workflow
Important defaults:
◦ Max persistence storage 10GB
◦ Max memory per shell 1GB
◦ Admin permissions required
Be very careful of changing this configuration
High Level
Workflow Configure-Server
{
#magic happens
}
PS C:> configure-server –pscomputername SRV01
Script
converted to
Workflow
XAML
Workflow
endpoint
Workflow
engine
Limitations and Gotchas
All objects
and data
must be
"serializable"
Must use full
cmdlet and
parameter
names –
these are
activities
No
positional
parameters
No Begin/
Process/End
scriptblocks
No
"eventing"
Limitations and Gotchas
No Traps -
Use
Try/Catch
Not intended
to be
interactive –
don’t use
Write-Host.
No comment
based help -
must use
MAML
formatted
files
Pay close
attention to
scope!
Workflow Architecture
Workflow Engine
PowerShell Client
Session
PowerShell
Workflow
“Service”
WinRM Client
Client
PSRP/PowerShell
Managed Node
Remoting
Commands/API
Operation Host Process
Operations
Host
WSMan/CIM
Managed Node
Building Workflows
Don't
simply
replace
"Function"
with
"Workflow"
Start new
and plan
out your
activities
Minimize
sharing of
data or
variables
across
activities
PowerShell
turns your
workflow
into XAML
Workflow is
a new
command
type in
PowerShell
3.0
PS C:> get-command -commandtype Workflow
Syntax: Sequence
Execute a collection of activities in order
Can be executed with Parallel
Watch out for scope!
Syntax: Sequence
Sequence {
MyCommand1
}
Sequence {
MyCommand2
MyCommand3
MyCommand4
}
This command runs
Then these commands run in sequence
Syntax: Parallel
Execute a collection of activities independently and in parallel
ForEach -Parallel
• The parameter only works in a workflow
• Run a set of commands in parallel for each object in a collection
Parallel key word
• Run a set of commands simultaneously and in parallel
• Runs in a new scope
• Often used to run a series of Sequences
Parallel
Parallel {
MyCommand1
MyCommand2
MyCommand3
Sequence {
MyCommand4
MyCommand5
} #sequence
} #parallel
These commands run in
sequence
Commands and
sequence run
simultaneously
ForEach -Parallel
ForEach -parallel ($item in $object) {
#do something with each object
MyCommand1 $item
MyCommand2 $item
}
For each item in the
collection…
Run these commands
All object processed
simultaneously
Syntax: InlineScript
Send PowerShell commands to remote machine(s)
Runs out-of-process
Runtime command validation
This is really a series of Invoke-Command activities
Use for all other non-activity commands
InlineScript
Workflow New-Audit {
Inlinescript {
$procs = Get-WmiObject Win32_process
$procs | Select-Object ProcessID,Name,
@{Name="RunTime";Expression={(Get-Date) -
$_.ConvertToDateTime($_.CreationDate)}},
@{Name="Owner";Expression={"$($_.GetOwner().Doma
in)$($_.GetOwner().User)"}}}
}
Syntax: Scope and Variables
Workflows uses static scopes, i.e. PowerShell won't
"search" for a variable
Assume each activity is isolated
Can use $Workflow:MyVar for “global” references
• Read-only
• Available from InlineScript
Access "out of scope" variables with $Using:MyVar
Syntax: Common Parameters
All workflows
have a set of
common
parameters They do not need
to be defined
•PSComputerName
•PSCredential
•PSConnectionRetryCo
unt
•PSActionRetryCount
•PSPersist
Syntax: Persistence
Workflows can be
made persistent to
survive interruptions
Planned reboots
Network interruptions
By default entire
workflow restarts
unless…
Set persistence per
activity
•Checkpoint-Workflow
•Persist
•Suspend-Workflow
Set persistence for
the entire workflow
-PSPersist common
parameter
Set to $True:
-pspersist $true
Running Workflows
Load
workflow
Specify
remote
computers
Specify
credentials
Run as a
job
Use a
Workflow
session
Invoke-AsWorkflow
Run any command or expression as a workflow
Run as an InlineScript
Executed from the console
Great for ad-hoc remote management without writing a workflow
Invoke-AsWorkflow -CommandName get-eventlog -
Parameter @{Logname="System";Newest=10;
Entrytype="Error"} -pscomputername $computers -asjob
Workflow Sessions
Run Workflows from within a special PSSession
Workflows can be monitored and managed from within the session
Great for long running workflows or those that might be suspended and
resumed
Session can be disconnected and reconnected
Best Practices
Try to test locally and interactively
Use Write-Verbose for tracing and troubleshooting
Use a workflow-aware editor like the PowerShell ISE
Take advantage of parallelism
Plan your activities…this is not just another way to script
Resources
The Lonely Administrator (http://jdhitsolutions.com/blog)
PowerShell in Depth
http://PowerShell.org
http://blogs.technet.com/b/heyscriptingguy
Thank You
http://jdhitsolutions.com/blog
jhicks@jdhitsolutions.com
@JeffHicks
http://plus.google.com/+JefferyHicks

Más contenido relacionado

La actualidad más candente

Gatling Tool in Action at Devoxx 2012
Gatling Tool in Action at Devoxx 2012Gatling Tool in Action at Devoxx 2012
Gatling Tool in Action at Devoxx 2012
slandelle
 

La actualidad más candente (20)

Reacting to the Isomorphic Buzz
Reacting to the Isomorphic BuzzReacting to the Isomorphic Buzz
Reacting to the Isomorphic Buzz
 
Angular Testing
Angular TestingAngular Testing
Angular Testing
 
What's New in Django 1.6
What's New in Django 1.6What's New in Django 1.6
What's New in Django 1.6
 
SpringMVC
SpringMVCSpringMVC
SpringMVC
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Gatling Tool in Action at Devoxx 2012
Gatling Tool in Action at Devoxx 2012Gatling Tool in Action at Devoxx 2012
Gatling Tool in Action at Devoxx 2012
 
Three Lessons about Gatling and Microservices
Three Lessons about Gatling and MicroservicesThree Lessons about Gatling and Microservices
Three Lessons about Gatling and Microservices
 
Backbone js
Backbone jsBackbone js
Backbone js
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
 
Spray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSpray - Build RESTfull services in scala
Spray - Build RESTfull services in scala
 
Why reactive:reactive programming spring 5
Why reactive:reactive programming spring 5Why reactive:reactive programming spring 5
Why reactive:reactive programming spring 5
 
Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2Reactive Thinking in Java with RxJava2
Reactive Thinking in Java with RxJava2
 
JavaScript Coding Guidelines
JavaScript Coding GuidelinesJavaScript Coding Guidelines
JavaScript Coding Guidelines
 
CQRS and Event Sourcing with Axon Framework
CQRS and Event Sourcing with Axon FrameworkCQRS and Event Sourcing with Axon Framework
CQRS and Event Sourcing with Axon Framework
 
Learn AJAX at ASIT
Learn AJAX at ASITLearn AJAX at ASIT
Learn AJAX at ASIT
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
The CQRS diet
The CQRS dietThe CQRS diet
The CQRS diet
 
Integrating AngularJS with Drupal 7
Integrating AngularJS with Drupal 7Integrating AngularJS with Drupal 7
Integrating AngularJS with Drupal 7
 
Marrying angular rails
Marrying angular railsMarrying angular rails
Marrying angular rails
 
PostgREST Design Philosophy
PostgREST Design PhilosophyPostgREST Design Philosophy
PostgREST Design Philosophy
 

Destacado

Ive got a powershell secret
Ive got a powershell secretIve got a powershell secret
Ive got a powershell secret
Chris Conte
 
PowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint adminsPowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint admins
Concentrated Technology
 
Managing enterprise with PowerShell remoting
Managing enterprise with PowerShell remotingManaging enterprise with PowerShell remoting
Managing enterprise with PowerShell remoting
Concentrated Technology
 

Destacado (20)

PowerShell Functions
PowerShell FunctionsPowerShell Functions
PowerShell Functions
 
No-script PowerShell v2
No-script PowerShell v2No-script PowerShell v2
No-script PowerShell v2
 
PowerShell and the Future of Windows Automation
PowerShell and the Future of Windows AutomationPowerShell and the Future of Windows Automation
PowerShell and the Future of Windows Automation
 
Ha & drs gotcha's
Ha & drs gotcha'sHa & drs gotcha's
Ha & drs gotcha's
 
Three cool cmdlets I wish PowerShell Had!
Three cool cmdlets I wish PowerShell Had!Three cool cmdlets I wish PowerShell Had!
Three cool cmdlets I wish PowerShell Had!
 
Meet Windows PowerShell
Meet Windows PowerShellMeet Windows PowerShell
Meet Windows PowerShell
 
PowerShell and WMI
PowerShell and WMIPowerShell and WMI
PowerShell and WMI
 
Combining output from multiple sources
Combining output from multiple sourcesCombining output from multiple sources
Combining output from multiple sources
 
Ive got a powershell secret
Ive got a powershell secretIve got a powershell secret
Ive got a powershell secret
 
PS error handling and debugging
PS error handling and debuggingPS error handling and debugging
PS error handling and debugging
 
Implementing dr w. hyper v clustering
Implementing dr w. hyper v clusteringImplementing dr w. hyper v clustering
Implementing dr w. hyper v clustering
 
VDI-in-a-Box: Microsoft Desktop Virtualization for Smaller Businesses and Uses
VDI-in-a-Box:  Microsoft Desktop Virtualization for Smaller Businesses and UsesVDI-in-a-Box:  Microsoft Desktop Virtualization for Smaller Businesses and Uses
VDI-in-a-Box: Microsoft Desktop Virtualization for Smaller Businesses and Uses
 
PowerShell 8tips
PowerShell 8tipsPowerShell 8tips
PowerShell 8tips
 
Best free tools for win database admin
Best free tools for win database adminBest free tools for win database admin
Best free tools for win database admin
 
PowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint adminsPowerShell crashcourse for Sharepoint admins
PowerShell crashcourse for Sharepoint admins
 
Basic PowerShell Toolmaking - Spiceworld 2016 session
Basic PowerShell Toolmaking - Spiceworld 2016 sessionBasic PowerShell Toolmaking - Spiceworld 2016 session
Basic PowerShell Toolmaking - Spiceworld 2016 session
 
Introduction to powershell
Introduction to powershellIntroduction to powershell
Introduction to powershell
 
PowerShell v4 Desired State Configuration
PowerShell v4 Desired State ConfigurationPowerShell v4 Desired State Configuration
PowerShell v4 Desired State Configuration
 
Managing enterprise with PowerShell remoting
Managing enterprise with PowerShell remotingManaging enterprise with PowerShell remoting
Managing enterprise with PowerShell remoting
 
PowerShell crash course
PowerShell crash coursePowerShell crash course
PowerShell crash course
 

Similar a Intro to PowerShell Workflow

PowerShell for SharePoint Admins
PowerShell for SharePoint AdminsPowerShell for SharePoint Admins
PowerShell for SharePoint Admins
Rick Taylor
 
Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application Server
Phil Windley
 
El camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - IntroductionEl camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - Introduction
Plain Concepts
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 
Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5
Billie Berzinskas
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
Power shell for sp admins
Power shell for sp adminsPower shell for sp admins
Power shell for sp admins
Rick Taylor
 

Similar a Intro to PowerShell Workflow (20)

Travis Wright - PS WF SMA SCSM SP
Travis Wright - PS WF SMA SCSM SPTravis Wright - PS WF SMA SCSM SP
Travis Wright - PS WF SMA SCSM SP
 
Ansible Automation to Rule Them All
Ansible Automation to Rule Them AllAnsible Automation to Rule Them All
Ansible Automation to Rule Them All
 
PowerShell 3.0 workflows
PowerShell 3.0 workflowsPowerShell 3.0 workflows
PowerShell 3.0 workflows
 
PowerShell for SharePoint Admins
PowerShell for SharePoint AdminsPowerShell for SharePoint Admins
PowerShell for SharePoint Admins
 
Working with data using Azure Functions.pdf
Working with data using Azure Functions.pdfWorking with data using Azure Functions.pdf
Working with data using Azure Functions.pdf
 
PowerShell-1
PowerShell-1PowerShell-1
PowerShell-1
 
Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application Server
 
Airflow presentation
Airflow presentationAirflow presentation
Airflow presentation
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 
El camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - IntroductionEl camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - Introduction
 
WF 4.0 Overview
WF 4.0 OverviewWF 4.0 Overview
WF 4.0 Overview
 
Power Shell for System Admins - By Kaustubh
Power Shell for System Admins - By KaustubhPower Shell for System Admins - By Kaustubh
Power Shell for System Admins - By Kaustubh
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
 
Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
SCU Asia System Center: Beyond orchestrator
SCU Asia System Center: Beyond orchestratorSCU Asia System Center: Beyond orchestrator
SCU Asia System Center: Beyond orchestrator
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Power shell for sp admins
Power shell for sp adminsPower shell for sp admins
Power shell for sp admins
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Intro to PowerShell Workflow

  • 2. Agenda What is Workflow? Workflow Syntax Running Workflows Practical Workflows Best Practices
  • 3. Think! Just because you can use a PowerShell workflow doesn’t mean you should.
  • 4. Definitions – What is a Workflow A robust multi-machine orchestration engine Designed for long running unattended tasks across potentially thousands of machines Persistent states can survive reboots and network interruptions Previously built in Visual Studio
  • 5. Definitions - What is PowerShell Workflow? • Persistence via check points • Suspend and Resume capabilitiesRobust • Parallel tasks • Connection pooling • Connection throttling Performance and Scalability • Use existing cmdlets* • No need to master XAML or use Visual Studio • Built in parameters for multi-machine management PowerShell Based
  • 6. Workflow Scenarios Server deployment Server configuration/remediation User provisioning Private cloud deployments Sharepoint configuration Any business workflow that can be orchestrated with command line tools.
  • 7. Key Workflow Concepts Workflow is a series of orchestrated activities Workflow activities are isolated All data and objects are serialized Objects are strongly typed Workflows use static scoping
  • 8. Requirements Built on .NET Framework 4.0 and Windows Workflow Foundation Requires PowerShell 3.0 Requires PowerShell 3.0 remoting Leverages PowerShell's job infrastructure
  • 9. Requirements: Remoting Workflows connect to machines using WSMan protocol Connects to the default Workflow session configuration PS C:> get-pssessionconfiguration microsoft.powerShell.workflow Important defaults: ◦ Max persistence storage 10GB ◦ Max memory per shell 1GB ◦ Admin permissions required Be very careful of changing this configuration
  • 10. High Level Workflow Configure-Server { #magic happens } PS C:> configure-server –pscomputername SRV01 Script converted to Workflow XAML Workflow endpoint Workflow engine
  • 11. Limitations and Gotchas All objects and data must be "serializable" Must use full cmdlet and parameter names – these are activities No positional parameters No Begin/ Process/End scriptblocks No "eventing"
  • 12. Limitations and Gotchas No Traps - Use Try/Catch Not intended to be interactive – don’t use Write-Host. No comment based help - must use MAML formatted files Pay close attention to scope!
  • 13. Workflow Architecture Workflow Engine PowerShell Client Session PowerShell Workflow “Service” WinRM Client Client PSRP/PowerShell Managed Node Remoting Commands/API Operation Host Process Operations Host WSMan/CIM Managed Node
  • 14. Building Workflows Don't simply replace "Function" with "Workflow" Start new and plan out your activities Minimize sharing of data or variables across activities PowerShell turns your workflow into XAML Workflow is a new command type in PowerShell 3.0 PS C:> get-command -commandtype Workflow
  • 15. Syntax: Sequence Execute a collection of activities in order Can be executed with Parallel Watch out for scope!
  • 16. Syntax: Sequence Sequence { MyCommand1 } Sequence { MyCommand2 MyCommand3 MyCommand4 } This command runs Then these commands run in sequence
  • 17. Syntax: Parallel Execute a collection of activities independently and in parallel ForEach -Parallel • The parameter only works in a workflow • Run a set of commands in parallel for each object in a collection Parallel key word • Run a set of commands simultaneously and in parallel • Runs in a new scope • Often used to run a series of Sequences
  • 18. Parallel Parallel { MyCommand1 MyCommand2 MyCommand3 Sequence { MyCommand4 MyCommand5 } #sequence } #parallel These commands run in sequence Commands and sequence run simultaneously
  • 19. ForEach -Parallel ForEach -parallel ($item in $object) { #do something with each object MyCommand1 $item MyCommand2 $item } For each item in the collection… Run these commands All object processed simultaneously
  • 20. Syntax: InlineScript Send PowerShell commands to remote machine(s) Runs out-of-process Runtime command validation This is really a series of Invoke-Command activities Use for all other non-activity commands
  • 21. InlineScript Workflow New-Audit { Inlinescript { $procs = Get-WmiObject Win32_process $procs | Select-Object ProcessID,Name, @{Name="RunTime";Expression={(Get-Date) - $_.ConvertToDateTime($_.CreationDate)}}, @{Name="Owner";Expression={"$($_.GetOwner().Doma in)$($_.GetOwner().User)"}}} }
  • 22. Syntax: Scope and Variables Workflows uses static scopes, i.e. PowerShell won't "search" for a variable Assume each activity is isolated Can use $Workflow:MyVar for “global” references • Read-only • Available from InlineScript Access "out of scope" variables with $Using:MyVar
  • 23. Syntax: Common Parameters All workflows have a set of common parameters They do not need to be defined •PSComputerName •PSCredential •PSConnectionRetryCo unt •PSActionRetryCount •PSPersist
  • 24. Syntax: Persistence Workflows can be made persistent to survive interruptions Planned reboots Network interruptions By default entire workflow restarts unless… Set persistence per activity •Checkpoint-Workflow •Persist •Suspend-Workflow Set persistence for the entire workflow -PSPersist common parameter Set to $True: -pspersist $true
  • 26. Invoke-AsWorkflow Run any command or expression as a workflow Run as an InlineScript Executed from the console Great for ad-hoc remote management without writing a workflow Invoke-AsWorkflow -CommandName get-eventlog - Parameter @{Logname="System";Newest=10; Entrytype="Error"} -pscomputername $computers -asjob
  • 27. Workflow Sessions Run Workflows from within a special PSSession Workflows can be monitored and managed from within the session Great for long running workflows or those that might be suspended and resumed Session can be disconnected and reconnected
  • 28. Best Practices Try to test locally and interactively Use Write-Verbose for tracing and troubleshooting Use a workflow-aware editor like the PowerShell ISE Take advantage of parallelism Plan your activities…this is not just another way to script
  • 29. Resources The Lonely Administrator (http://jdhitsolutions.com/blog) PowerShell in Depth http://PowerShell.org http://blogs.technet.com/b/heyscriptingguy