Introduction to windows power shell in sharepoint 2010


Published on

2nd SPS Vietnam from Gia Mai

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • What => Why => Who => Where => When => How
  • What is Shell?Working with a command-line interface, often called a shell, can be a daunting task. If you grew up working with DOS or Unix-based system, you'll feel right at home with PowerShell.If you're used to a computer that always presents you with a Graphical User Interface(GUI), then typing your commands into PowerShell may seem like going backward in time. After you become familiar with a command-line user interface, however, don't be surprised if you get fond of the speed, flexibility, and robustness you find there; you may get a hooked.What is PowerShell?Unix-like shellObject oriented.NETCommand lineScripting languageA single mindset for management of many different systems (e.g.: AD, Exchange, Windows)Extensible framework that can be embedded inside other applications
  • Over the last few years, PowerShell scripting has begun to replace older DOS-style batch files and VBScript files as the preferred way to manage and automate administrative tasksCmdlets are callable functions Pipelining allow one Cmdlet to return an object as input to anotherPowerShell includes formatting features to display output using lists or tablesPowerShell is based on a provider-based model based on Snap-insSharePoint support added through Microsoft.SharePoint.Powershell..Snapin: Group of PowerShell functionality
  • Previous version of WSS relies on STSADM.EXEUsed for command line administration and scriptingPSDrivesFileSystem Provider- access to the file systemMap to key SharePoint directoriesSTSADM via PowerShellExecute operations via the PowerShell hostIntegrate STSADM operations into the pipelineScripting via Object ModelAccess SharePoint objectsCreate reusable SharePoint-aware commandsCustom DevelopmentCmdLetsProvidersHost ApplicationsAutomated build and deploy: => Save time for Deploy/Test Cycle phases
  • This is expensive! The first operation essentially iterates over every site twice—AND it has to start and stop the stsadm logging/process/etc for each feature activation!!The first took 12+ hours and NEVER FINISHED.The latter took roughly 30 minutes.
  • Automation: using Task Scheduler for running Backup and Restore.Development:Testing: usingPowerShell for stress test
  • The first example shows calling a Cmdlet that takes no parametersThe second example adds filtering by adding a Where commandWhere-Object {$ –eq "F*"}The syntax $_ refers to the object in question$ refers to the object's name property-eq is the operator for equalsThe third example adds in formatting instructionsThe last example redirects output so it is stored in a new text files.
  • Get-Help cmdlet
  • You can use aliases to save yourself the time and effort of typing cmdletsthat you use frequently. If you want to see all the aliases that PowerShell has mapped to specific cmdlets, use the Get-Alias cmdlet.
  • By default, PowerShell does not allow script to runAdministrator must change execution policy to enable script executionExecution Policy Settingsrestricted (default) – scripts prohibited from executingunrestricted - scripts can execute. Scripts that are signed can run with user interaction. Scripts that are not signed result in prompting user for permission to execute.bypass (developer mode) – scripts can execute and user interaction is suppressed.
  • With the initial release of PowerShell, administrators and developers usually resorted to writing scripts with NotePad. PowerShell 2 provides a nice development environment for writing PowerShell scripts named the PowerShell Integrated Scripting Environment (ISE). When it comes t writing complex scripts with control of flow logic, it is really nice to be able to debug and single step through your code.
  • Thisexample shows a PowerShell script which uses the New-SPSite cmdlet to create a new site. You should observe that the New-SPSite cmdlet returns a SPSite object which is then used to access the SPWeb object for the top-level site.
  • SharePoint Server 2010 adds many Cmdlets for SharePoint administration through a Snap-in provider named Microsoft.SharePoint.PowerShell. The SharePoint cmdlets cannot be called until the SharePoint snap-in has been loaded.There are two common ways to load the SharePoint snap-inCall the Add-PSSnapin cmdlet and pass a parameter with the snap-in nameLaunch the PowerShell console using SharePoint Management Console. This link points to an XML file that loads the SharePoint snap-in in a declarative fashion.
  • Introduction to windows power shell in sharepoint 2010

    1. 1. Introduction to Windows PowerShell in SharePoint 2010<br />Gia Duy Mai<br />Solutions Assistant Lead<br />Bamboo Solutions<br />
    2. 2. Agenda<br />Introduction to PowerShell<br />Why PowerShell for SharePoint?<br />When use PowerShell?<br />PowerShellvs STSADM<br />Getting started with PowerShell<br />Controlling PowerShell with variables, loops, logic, and functions<br />Creating your own PowerShell scripts <br />Scheduling your PowerShell scripts<br />Demo<br />Q&A<br />
    3. 3. Introduction to PowerShell<br /><ul><li>What is Shell?</li></ul>Working with a command-line interface, often called a shell<br /><ul><li>What is PowerShell?
    4. 4. A modern replacement for the CMD (command) shell
    5. 5. PowerShell works with objects
    6. 6. PowerShell integrates with the .Net Framework
    7. 7. PowerShell is based on a provider-based model
    8. 8. A powerful scripting environment for administration</li></li></ul><li>PowerShell Fundamentals<br />Scripts<br />PowerShell code in a PS1 (similar to .bat files)<br />CmdLets<br />A PowerShell command is called CmdLets<br />Like Features in SharePoint, performs a task<br />Can be compiled or in script<br />Ex: Get-Process and Stop-Process<br />Snapins<br />Like Solutions in SharePoint, they hold a lot CmdLet<br />Compiled into dlls<br />Ex: Microsoft.SharePoint.Powershell<br />Pipelining <br />Formatting features<br />Provider-based model for accessing resources<br />
    9. 9. The Pipeline<br />What is Pipeline?<br /><ul><li>The most unique feature of PowerShell
    10. 10. Pipelining allow one Cmdlet to return an object as input to another</li></ul>C#: <br />X = Class.Method();<br />Y = OtherClass.Method(X);<br />Z = OtherOtherClass.Method(Y)<br />PowerShell:<br />Class.Method() | OtherClass.Method() | OtherOtherClass.Method()<br />
    11. 11. Why PowerShell for SharePoint 2010? <br />Automated build and deploy<br />Rapid prototyping<br />Remoting interface<br />Administration automation<br />Easy for controlling, manipulating and modifying our SharePoint environment<br /><ul><li>PowerShell support effectively replaces STSADM</li></ul>STSADM.EXE<br />We’ll miss you old friend<br />
    12. 12. PowerShell vs STSADM<br />
    13. 13. PowerShell vs STSADM - Performance<br />Performance benefits for batch operations<br />STSADM Batch Operation<br />PowerShell Cmdlets in Batch<br />Start Thread<br />New STSADM Execution<br />Start Thread<br />Load DLLs<br />Start logging<br />Repeat<br />Start Logging<br />Execute Command<br />Repeat<br />Execute Command<br />Stop logging<br />Stop Logging<br />Stop Thread<br />Close STSADM & Thread<br />
    14. 14. PowerShell vs STSADM - Performance<br />PowerShell “Wrapped” STSADM to enable a feature on every SPSite<br />Same command in SharePoint 2010 PowerShell:<br />$rawdata = stsadm.exe -o enumsites -url $WebAppURL <br />$sitexml = [XML]$rawdata<br />$sitesxml.Sites | foreach-object{ $_.Site } | foreach-object{<br />  stsadm -o activatefeature -url$_.url -filename $featureFileName<br />         if( $lastexitcode -ne 0 ){ <br />            Write-Host “Failure:$lastexitcode n" -Fore Red;<br />            $failure = $true; <br />         }<br />}<br />12+ Hours<br />(5300 SPSites)<br />30 Minutes<br />(5300 SPSites)<br />Get-SPSite –Limit ALL –WebApplication $WebAppNameorUrl |%{ <br />Enable-SPFeature$FeatureIdOrName –url $_.Url <br />}<br />
    15. 15. When use PowerShell?<br />When you want to make your team more agile<br /> - Automation, automation, automation<br /><ul><li>Development phase</li></ul> - Using PowerShell to save time for Build/Deploy/Test Cycle<br />Testing phase<br />Using the PowerShell scripts to stand up an environment for running tests<br />Traditional SharePoint Development<br />Wasted time for testing<br />When you use PowerShell<br />
    16. 16. Who should learn PowerShell?<br /><ul><li>SharePoint Admins/Devs should learn PowerShell basics</li></ul>Why you should learn PowerShell?<br />Microsoft says it’s important<br />You can’t do everything from the GUI any more<br />It can make your life easier<br />Most Microsoft products will eventually use it<br />Microsoft certification exams contain PowerShell questions<br />Improve your job<br />It’s not going away anytime soon<br />
    17. 17. Getting Started with PowerShell<br />(1) Execute a Cmdlet<br />(2) Filter results using where clause<br />(3) Add formatting instructions<br />(4) Redirect output to new text file<br />
    18. 18. Getting Help in PowerShell<br />
    19. 19. Controlling PowerShell with variables, loops, logic, and functions<br />
    20. 20. Variables in PowerShell<br />A variable is a place for you to store some value so you can revisit it later.<br />All variables that you create begin with $<br /> Ex: $my_first_variable= “Hello World”<br />Variables Types<br /> Loosely typed variables<br />$f = “bar” #implicitly typed as string<br />$ary= 4,2,5,2 #typed as object[]<br /> Strongly typed variables<br />[string]$f = “bar”<br /> Enhanced Types variables<br />[xml]$d = “<a><b><c>c stuff 1</c><c>c stuff 2</c></b></a>”<br />
    21. 21. Looping in PowerShell <br />Classic PowerShell Loop<br />- For Loop<br />$i = 10 <br />For($j = 1; $j-lt $i; $j++){ Write-Host ”$j”; }<br />- ForeachLoop<br /> $NumArray= (1,2,3,4,5,6,7,8,9,10)Foreach($Item in $NumArray) {$Item * 3}<br /> - While Loop<br />$i =8 While ($i-le 96) { $i+=8; Write-Host$i; }<br /> - Do Until Loop<br />$i = 7; <br />do { $i+=7; Write-Host$i; } until ($i-gt 85)<br />ForeachLoop with Pipeline<br />Get-SPSite -Limit All | foreach { <br />Remove-SPSite -identity $_.Id }<br />$_ and is a variable that represents the current object<br />
    22. 22. Adding logic in PowerShell <br />Logic is what enables you to do something at a specific point in the program.<br />Statements<br />If/ ElseIf/ Else<br />Switch<br />While <br />Comparison Operators<br />-eq/-ne<br />-lt / -gt<br />-le / -ge<br />-like / -notlike<br />-contains/-notcontains<br />-replace<br />…<br />
    23. 23. Working with PowerShell functions<br />FunctionListRootDrive($DriveLetter)<br /> { Get-ChildItem–Path $DriveLetter}<br />Function ListRootDrive<br /> { Get-ChildItem–Path $Args}<br />FunctionListRootDrive<br /> { Get-ChildItem–Path $Args[0] }<br />FunctionBlogUsers($SiteCollection) {<br />Get-SPWeb-Site $SiteCollection| ForEach-Object { Write-Host “Site Title: “ $_.Title<br />if ( $_.Title -eq “Blog” ) { Write-Host “Blog Users:” $_.Users<br />}}}<br />
    24. 24. PowerShell Aliases<br />PowerShell commands are usually long. However, PowerShell has aliases. You can use aliases to save yourself the time and effort of typing cmdlets<br /><ul><li>Get-ChildItem ~ dir
    25. 25. Foreach-Object ~ %
    26. 26. Get-ChildItem|foreach-object { $_.Name }
    27. 27. Alias: dir|% { $_.Name }
    28. 28. Where-Object ~ ?
    29. 29. Get-ChildItem|where-object{$_.Length –gt10}
    30. 30. Alias: dir|?{$_.Length –gt10}</li></ul>You can find these aliases with the Get-Aliascmdlet<br />
    31. 31. Creating your own PowerShell scripts <br />
    32. 32. Tools<br />Notepad<br />PowerShell Command<br />Windows PowerShell Integrated Scripting Environment (ISE)<br />PowerGUI<br />- Download from<br />
    33. 33. How to Create and Run a PowerShell Script <br />The steps to create a script follow:<br />Create the script in Notepad and save with a .PS1 file extension (hello.ps1).<br />Run the script by entering the full path to the script (c:scriptshello.ps1), or if it’s in the current directory (.hello.ps1).<br />If the path to the script contains a space, enclose the full path in quotation marks and prefix the entire thing with an ampersand ("C:my scriptshello.ps1").<br />
    34. 34. Scripts and Execution Policy<br />Local execution policy must be configured<br />Scripts will not execute under default execution policy of restricted<br />Scripts can execute under execution policy of unrestricted. Scripts that are not signed result in prompting user for permission to execute.<br />Scripts can execute under execution policy of bypass. This mode suppresses prompting user for permission to execute.<br />
    35. 35. Editing Scripts using PowerShell ISE<br />Supports Color-coding, IntelliSense and debugging<br />Writing scripts here<br />Run cmdlets or functions here<br />Results<br />
    36. 36. Examples of SharePoint Scripting<br />
    37. 37. The SharePoint PowerShell Snapin<br />Explicitly load SharePoint PowerShell snap-in from console or script<br />Implicitly load SharePoint PowerShell snap-in by using SharePoint 2010 Management Shell<br />Begin using SharePoint Cmdlets<br />
    38. 38. Scheduling Your Scripts<br />Sometimes commands need to be scheduled to run automatically<br />PowerShell Scripts (.ps1) can be scheduled using Task Scheduler<br />Just put the above command into a .bat or .cmd file and schedule it like you would normally schedule a script to be run with Task Scheduler.<br />
    39. 39. Demo – Series Of Scripts<br />Run hello.ps1 script<br />How to use PowerShell to create sites.<br />How to use PowerShell to populate items in a List for testing, adding attachments<br />How to use PowerShell to copy items from one list to another.<br />How to use PowerShell to upload documents to a document libraries.<br />How to use PowerShell to backup sites.<br />
    40. 40. Q&A<br />
    41. 41. Resources<br /><br /><br /><br /><br /><br />
    42. 42. THANK YOU!<br />
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.