Introduction to PowerShell - Be a PowerShell Hero - SPFest workshop

Post on 18-Nov-2014

430 views 4 download

Tags:

description

The slides from Michael Blumenthal's and Jack Fruh's "Be a Hero with PowerShell" workshop at SharePoint fest, a comprehensive introduction to using PowerShell with SharePoint.

Transcript of Introduction to PowerShell - Be a PowerShell Hero - SPFest workshop

Introduction to PowerShell for SharePoint Developers and

Administrators

Michael Blumenthal & Jack Fruh

2

Who is Michael Blumenthal?

Sr. Solution Architectat PSC Group

CSPUG Co-LeaderINETA Champ 2010-201318 years in IT Consulting10 years working with

SharePoint (2003,2007,2010, 2013)

3

Who is Jack Fruh?

SharePoint AdministratorFortune 500 Company

Big on communitySPS Chicago Suburbs Co-LeaderSharePointJack.comSPYamSharePoint-Community.org

4

This is about you

Version of SharePoint?Admin, Developer, Both, Other?PowerShell experience?SharePoint experience?

5

No Compiling!

No Packaging!

Just Code & Go!

Why PowerShell?

6

PowerShell puts the SharePoint Engine at your fingertips!

•It’s Easy to Get Started!1•Learn the PowerShell Syntax2•Real World Examples3•More Resources4•Demo!5

7

Chapter 1

IT’S EASY TO GET STARTED!

Getting Started with PowerShell

Windows Server 2003• Download

Windows Server 2008• Install

Server2008 R2, 2012, Win8• Run (Add ISE)

9

10

11

V2

12

PowerShell V3 ISE

13

POSH vs the SharePoint Mgmt Shell

14

Chapter 2

LEARN THE POWERSHELL SYNTAX!

Learn to use PowerShell with SharePoint!

Symbols & Keywords

Using the SharePoint API

Creating and Running Scripts

16

Symbols, Keywords, and Syntax! Oh My!

•Variables1•Commands2•Piping3•Comparisons4•Flow Control5•Filtering6

17

Punctuation PronunciationSymbol Called Symbol Called

$ Dollar sign, money _ Underscore

# Hash, Pound [ ] Square Brackets

| Pipe, vertical bar . Dot, point, period

{ } Curly braces < > Angle Brackets

“ Double Quote, tick - Dash, hyphen, minus

: Colon % Percent sign

( ) Parentheses ; Semi-colon

+ Plus = Equals, is

! Bang, not /, \ Slash, backslash

1$#|

18

Variables begin with a $

$foo

• Case Insensitive, Dynamic typing

$true, $false, $profile, $null

$foo = “Hello, World”

1

19

20

Commands are called cmdlets.

Verb-Noun

Built-in, Extensible

Get-Help & Help

Get-Member

2

21

22

The Power of Piping!

Output Of Command

1

Input of Command

2|

3

Example

Making Comparisons4Operator Meaning Operator Meaning

-eq Equals -le Less Than or Equal To

-ne Not Equals -like Wildcard Match

-gt Greater Than -notlike Not (Wildcard Match)

-ge Greater Than or Equal To

-match Reg. Exp. Match

-lt Less Than -notmatch Not (Reg. Exp. Match)

25

Example

26

Taking Control of the Flow5

•For (Init;Test;Repeat) {Commands}•for($i=1; $i -le 10; $i++) {Write-Host $i}For•Foreach (Item in Collection) {Commands}•Foreach ($web in $site.AllWebs) {$web.Title}ForEach•If (Test) {Commands} •if ($web.Title –ne “”) {Write-Host $web.Title}If•While (Condition){Commands}•while($val -ne 3){$val++; Write-Host $val}While

Example

28

Where-Object6

•Where {<Test>}Syntax

• V1&2:Dir | Where {$_.Name –like “B*”}

• V3:Dir | where Name –like B*

Example

DEMO

Directory Sorting

30

Using the SharePoint API

•Getting an SPSite1•Manipulating It2•Cleaning Up3

31

Highlights from the SharePoint Object Model

SPSite

32

Loading SharePoint Cmdlets

Even in MOSS 2007:[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

Loading SharePoint DLLs

C:\...\14 or 15\CONFIG\POWERSHELL\Registration\

SharePoint.ps1

33

DEMO:ISE needs to load snapin

34

Get a Site and Explore it!

$site = get-spsite http://server/path

THEN$site

35

DEMO

Web, Site, Lists

37

A Word About Memory ManagementSPWeb

SPSite

Inline

In Script

Dispose

38

39

BREAK

40

Chapter 3

REAL WORLD EXAMPLES

41

Practical Uses• Bulk Create Sites1• List Item CRUD2 •Create data for test cases3

• Associate Workflows with a List4 •Work across site collections

5•Deployment Scripting6•Identify files that won’t upload7

42

More Practical Uses• Sync Wep App Properties8• Install SharePoint9• Repeatably Manage Content10• Update Field Definitions11• Edit MP3 Metadata, Make Flashcards12

43

Real World Examples

Check the Farm VersionCreate List ItemsBulk Site CreationPost Deployment Build Scripts with Audio AlertsDocument Versioning Settings (later)

44

What’s your SharePoint Version?

PS C:\Users\Administrator> $(get-SPFarm).BuildVersion

Major Minor Build Revision----- ----- ----- --------14 0 6109 5002

DEMO

Farm & Build Ver

46

Create a List Item

DEMO

Create New Item

48

Audio Alerts

Stick this at the end of your long running script:

$Voice = new-object -com SAPI.SpVoice $Voice.Speak(“Deployment is done!")

49

Email Alerts

Send-MailMessage [-To] <string[]> [-Subject] <string> [[-Body] <string>] [[-SmtpServer] <string>] -From <string> [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Encoding <Encoding>] [-Cc <string[]>] [-DeliveryNotificationOption <DeliveryNotificationOptions>] [-Priority <MailPriority>] [-Credential <pscredential>] [-UseSsl] [-Port <int>] [<CommonParameters>]

50

Executing Scripts

.\filename.ps1

Set-ExecutionPolicy Unrestricted

DEMO

Run a Script – See Exec Pol

52

Chapter 4

TOOLS & BEST PRACTICES

53

Tools and Best Practices

•Tools 1•Best Practices2•Resources3

Tools

ISE• Add Windows Feature

PowerShell Plus - Idera• SP2010 focused

PowerGui• Pro version Too

PowerShell Studio - Sapien• Not Free

Visual Studio 2012

55

ISE, ISE Baby

Microsoft’s

Available Since POSH V2• SP2010 -> POSH 2; SP2013 -> POSH 3

OS Feature

56

You might have to add the ISE

57

V2Use With SP2010

58

PowerShell V3 ISE - for SP2013

59

POSH vs the SharePoint Mgmt Shell

POSH + SnapIn = SharePoint Management Shell

60

Where is it?

61

62

Demo – ISE Debugging

63

Visual Studio 2012 Update 3Integration with TFSFor SharePoint developers, tool of choiceAdd-ons available

64

65

66

67

PowerGUI

Created for POSH v1 originally

Free & large community support

Lots of Add-ons• SCCS in Pro

68

69

PowerGUI screen shot

70

Idera’s PowerShell Plus

Free with ads for Idera’s other productsIncludes support for SP2010, but not 2013

Framework Dependecy….Lots of features…. Bloated Overkill?

71

72

Sapien’s PowerShell Studio

Trial requires special trial license in a VMDoes create a POSH Library

73

74

Sapien Bonus

75

Conclusion on POSH IDEs

76

BREAK

77

Best Practices

• Follow the Verb-Noun pattern1• Comment Your Functions2• Write your scripts as functions that

announce themselves• Make accidentals runs harmless

3• Use Source Control4

78

Verb-Noun = Action-Thing

Add Backup Clear Connect Convert Copy Disable Disconnect Dismount Enable

Etc…

SPAppDeniedEndpoint SPClaimTypeMapping SPDiagnosticsPerformanceCounter SPDistributedCacheServiceInstance SPEduClassMember SPEduUser SPInfoPathUserAgent SPPluggableSecurityTrimmer SPProfileLeader SPProfileSyncConnection

Etc…

42 verbs combined with 347 nouns to give us 799 cmdlets

79

Comment your functions

<#.SYNOPSIS –a brief explanation of what the script or function does..DESCRIPTION – a more detailed explanation of what the script or function does..PARAMETER name – an explanation of a specific parameter. Replace name with the parameter name. You can have one of these sections for each parameter the script or function uses..EXAMPLE – an example of how to use the script or function. You can have multiple .EXAMPLE sections if you want to provide more than one example..NOTES – any miscellaneous notes on using the script or function..LINK – a cross-reference to another help topic; you can have more than one of these. If you include a URL beginning with http:// or https://, the shell will open that URL when the Help command’s –online parameter is used.

#>

80

81

Find custom commands this way

Refresh the command list

Actions you can take once you fill in parameters

82

More Good Ideas

Always read scripts before running themMake it safe for others to not read them firstWrite scripts as functions most of the timeCheck for valid parameter values Do error handling

83

Demo

Writing FunctionsUsing Comments for Documentation

TFS DEMOCheck In, Out, Diff

85

MORE EXAMPLES

86

Now for More Examples

Jack’s take on Doc Lib Versioning – reporting & settingBulk Site CreationEmailLoggingSSL Cert Expiration WarningDeploy WSPs

DEMO

Doc Lib Versioning

88

Bulk Site Creation

Site Definitions in V. StudioNot an answer by themselvesDefine site contentIntended for reuse

Mismatch to one time needCAML and PITAHarder: Making it data drivenChange Site Def -> Recreate Site

PowerShell & Excel & UI

Well suited for one time “blow in’s”Define the site template in the UI or use standardSave as a template

Even pub sites - sometimesPowerShell has easy loopsData driven from a CSVChanges -> Mod Scripts

89

The PowerShell Solution

Read the list of sites from CSVLoop:

Create SiteConfigure Site

Turn on FeaturesSet Master Pages, Welcome PageHide Libraries, set versioningAdjust Navigation

Add Lists, Libraries, Pages, Web parts, etcLoop again & again if needed – iterative!

DEMO

Bulk Site Creation

Jack’s Favorite Scripts

Logging, Deployment, & more

92

Chapter 5

MORE RESOURCES

Resources

Microsoft Resources

3rd Party Resources

95

96

97

98

99

100

101

JEFF HICKS

102

Resources SummaryMSFT

PowerShell Product Team Blog Script Center

CommunityVarious BooksCodePlex: PSBBs (mine), CodePlex:SPInstaller Blog.BlumenthalIT.NetSharePointJack.comJeff Hicks , Gary LaPointe, Raymond Mitchell, Todd Klindt, POSHCODE.ORG, get-spscripts.com SPYam

103

Script something today!

It’s Easy to Get Started!

Learn & Use the PowerShell Syntax

More Resources

In Review…

104

Questions & Thank You

• Michael BlumenthalSharePoint ArchitectPSC Group, LLC

• MBlumenthal@psclistens.com• psclistens.com• www.cspug.org• Twitter:

@MichaelBL• SPYam

• Jack FruhSharePoint Admin

• Jack@SharepointJack.com

• SPSChicagoSuburbs.com• SharePointJack.com• Twitter:

@SharePointJack• SPYam

Thank you for your time today.