advanced powershell scripting jeffrey p. snover partner architect
TRANSCRIPT
Advanced PowerShell ScriptingJeffrey P. SnoverPartner Architect
Agenda
State of the SoftwareCommunity Technology PreviewForms and Styles of Scripting V1 Advanced Scripting Techniques
ScriptblocksSwitch
V2 Advanced Scripting TechniquesCmdletsPSJobs
Warning: this will do DEEP and FAST quickly
State of the SoftwarePhenomenal rate of adoption
> 1.55 Million downloads in < 1 yearExchange 2007, MOM 2007, Virtual Machine Manager 2007, Lotus Domino Transporter Suite, Data Protection Manager, Compute Cluster Tool Pack, Windows Server, BackupGood ISV pickup> 20 new internal partners
CEC 2009 requirementWon both Best of TechEd and Teched Attendees Pick
State of the Software - CommunityActive and useful Newsgroups and Forums
25 Codeplex projects (2 in the top 25 most active)Strong group of MVPsStrong community tools
Tower of Power
Announcing : PowerShell V2 Community Technology Preview (CTP)
Availability /Applicability
The PowerShell V2 CTP is not for everyoneRead this PowerShell Team blog entry:
http://blogs.msdn.com/powershell/archive/2007/11/02/ctp-watch-this-space.aspx
PowerShell V2 Themes
Universal Code Execution Model
GUI over PowerShell
Production Scripting
Community Feedback
Call To Action
Read the PowerShell blog Download PowerShell CTP
On non-production systems
Kick the tires and let us know what we got right/wrongLet us know about any incompatibilities with V1
Forms of Scripting
ScriptsFiltersFunctionsCmdlets [New in V2]
Styles of Scripting
Ad HocRun at the command line
Simple BASH styleParameters are not named or typed
FormalParameters are named, typed, have initializers
SophisticatedRich error handlingSupport –Verbose, -Debug, -Confirm, -WhatifDigitally signed
Styles of Scripting
Jeffrey SnoverWindows Management Partner Architect
demo
Script Blocks
Script is a first class datatypeAlready used in lots of the utilities and infrastructureScriptBlocks can have parametersYou can pipeline to ScriptBlocks using BEGIN,PROCESS,END code blocks
$x={BEGIN{$x=0} PROCESS{$x++; write-verbose “$x $_”}}Get-Process |&$x
Scriptblocks can be parameters[ScriptBlock]$AssemblyFilter
Scoping depends upon invocation. $x #Runs in current scope& $x #Runs in a new scopeInvoke-Command $x # Runs in a new scope
ScriptBlocks
Jeffrey SnoverWindows Management Partner Architect
demo
Switch
Queen of Control statementsCombines pattern matching, branching and iterationCan operate on a singleton or a collectionVERY rich pattern matchingCan process an entire file
Switch –options (<pipeline>){ <Pattern> { <StatementList> }
<Pattern> { <StatementList> }default { <StatementList> }
}
Switch
Jeffrey SnoverWindows Management Partner Architect
demo
Script Cmdlets
Functions, Filters, CmdletsSupports most everything a .NET Cmdlet can do
Attributes on Cmdlet
-SupportsShouldProcess-ConfirmImpact {Low|Medium|High}
Attributes on Parameters$CMDLET similar to a C# THIS
$Cmdlet.ShouldProcess(“Target”, “Action”)$Cmdlet.ShouldContinue(“Query”, “Caption”)
Engine does a TON of work for you Drives consistent syntax and semantics
Parameter Attributes
MandatoryPosition(int)Alias(string)ValueFromPipeline, ValueFromPipeLineByNameAllowNull, AllowEmptyString, AllowEmptyCollectionValidateRange(int,int), ValidateLength(int,int) , ValidateNotNull, ValidateNotNullOrEmpty, ValidatePattern(regex), ValidateSet(string[],bool), ValidateCount(int,int), ValidateScript(scriptblock)Customer attributes supported as wellParameterSets are not supported in this CTP
$cmdlet
MethodsCurrentProviderLocation, GetResolvedProviderPathFromPSPath, GetResourceString, GetUnresolvedProviderPathFromPSPath, GetVariableValueInvokeShouldContinue, ShouldProcessThrowTerminatingError, WriteCommandDetail, WriteDebug, WriteError, WriteObject, WriteProgress, WriteVerbose, WriteWarning
PropertiesCommandOrigin, CommandRuntime, Host, InvokeCommand, InvokeProvider, JobRepository, MyInvocation, ParameterSetName, SessionState, Stopping
ScriptCmdlet – Engine Functions
-OutVariable-ErrorAction , -ErrorVariable-Whatif, -Confirm, -Verbose-Debug
ScriptCmdlets
Jeffrey SnoverWindows Management Partner Architect
demo
V2 – Universal Code Execution Model• Commands, expressions and ScriptBlocks can
be run• in the foreground or background • on one or more machines• over a LAN or a WAN• in unrestricted or restricted environments• using short or long connections• using impersonation or supplied credentials• initiated by user input or by events
Universal Code Execution Model
Foreground Background
Local Invoke-Expression Start-PsjobWait/Receive/Stop
Remote / Remote many
-ComputerName <name[]>-Runspace <runspace[]>-Throttle <int>-PSCredential-ShellName<Connection info [port, useSSL, shellid]>
-ComputerName <name[]>-Runspace <runspace[]>-Throttle <int>-PSCredential -ShellName <Connection info [port, useSSL, shellid]>
Background Jobs
Commands, expressions and scriptblocks can be run in the foreground or background on one or more machinesPSJOB – Start, Get, Wait, Receive, Stop, RemoveProvide a runspace or it will create a local runspace connectionJobs can contain ChildJobs
Operate on them individually or collectively
Summary/Call to ActionNow available at: www.microsoft.com/downloads
Search for PowerShell
Try it, Deploy it, Use it, Share
Community ResourcesNewsgroup: Microsoft.Public.Windows.PowerShellTeam blog:
http://blogs.msdn.com/PowerShell/PowerShellCommunity.Org:
http://www.PowershellCommunity.OrgChannel 9
http://channel9.msdn.com/tags/PowerShellWiki
http://channel9.msdn.com/wiki/default.aspx/Channel9.WindowsPowerShellWiki
Script Center:http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
CodePlex:http://codeplex.com/Project/ProjectDirectory.aspx?TagName=powershell
Many excellent booksManning Press book by PowerShell Dev Lead Bruce Payette: PowerShell in Action
http://manning.com/powershell/ O’Reilly book by PowerShell Dev Lee Holmes – Windows PowerShell Cookbook
http://www.oreilly.com/catalog/9780596528492/index.html
Questions?
Complete your evaluation on the My Event pages of the website at the CommNet or the Feedback Terminals to win!
All attendees who submit a session feedback form within 12 hours after the session ends will have the chance to win the very latest HTC 'Touch' smartphone complete with Windows Mobile® 6 Professional
© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the
date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.