Tuesday, August 14, 2012

How to create and run your first SharePoint Powershell script

As of late, I've been playing with Powershell quite a bit and thought I'd begin sharing some of the code samples that I've created and shared with our SharePoint Admin team.  For starters, I'd like to begin the journey by teaching those of you unfamiliar with Powershell how to create a simple script as well as execute it.  In this example, I'm going to create a script that performs several common actions that you're likely to run into when scripting in Powershell which are listed as follows:

  • Attach the Microsoft SharePoint assembly so that you can reference commonly used APIs
  • Accept input from the user
  • Write information to the console
  • Pause the window so that it doesn't close immediately after the script is run

When executed this script will do the following:

  • Prompt the user for the link to a site collection he/she would like to view a list of all sites contained under (i.e. http://SharePointWebApplication)
  • Write out the list of sites contained under the site collection to the console
  • Prompt the user to press any key to close the console

Creating a Powershell script:
  1. Open Notepad
  2. Copy and paste the following code into it:

  3. [System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    $siteCollectionURL = Read-Host "Enter the URL of the Site Collection"
    $site = new-object Microsoft.SharePoint.SPSite($siteCollectionURL)
    
    foreach ($webs in $site.AllWebs)
    {
     Write-Host "URL:", $webs.Url
    }
    $site.Dispose()
    
    $Input = Read-Host "Please press any key to close the window"
    

  4. Click File -> Save As...
  5. Navigate to the directory you'd like to save your script under
  6. For File name:, enter a name for your file and add .PS1 to the end of it (i.e. ListAllSiteUnderSiteCollection.PS1)
  7. For Save as type:, select All Files
  8. Click Save

Executing the script:
  1. Right-click Start -> Open Windows Explorer
  2. Navigate to the directory where you just save your script
  3. Right-click on the script file and select Run with Powershell

Modifying the script:
  1. Right-click Start -> Open Windows Explorer
  2. Navigate to the directory where you just save your script
  3. Right-click on the script file and select Open With -> Notepad

I'll be certain to provide more scripts in the future, but at least wanted to start with the basics so that you'll know what do when you see them show up on my blog from time to time.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.