SharePoint 2007 and PowerShell

Module #06: PowerShell With SharePoint Lab #02

 

Course:                SharePoint
2007 Operations

Estimated Time to Complete:  60 minutes

Objectives:

·        
Load SharePoint Dll
into PowerShell

·        
Set PowerShell
Execution Policy

·        
Enumerate Webs

·        
Create a site with
PowerShell

·        
Create/Update an
item with PowerShell

·        
Backup SharePoint
with PowerShell

Operating
Notes:
 

·        
Run
this lab on the svr-sp2 image

·        
You
should be logged in as trainingadministrator


Deliverables:

·        
None

 

Overview:         Learn
to write PowerShell scripts for common SharePoint Tasks!

Exercise 1 – Write a PowerShell Script (Load SharePoint Dlls)

Purpose:
        Learn
to load the SharePoint dlls

Result:           
A PowerShell environment with SharePoint .NET
dlls loaded

Task 1 – Load the
SharePoint dlls

  1. Be sure to
    login to svr-sp2 as trainingadministrator
  2. Open a
    command prompt, start powershell:


Powershell

  1. Type the
    following:


[AppDomain]::CurrentDomain.GetAssemblies() | foreach-object {
split-path $_.Location -leaf } | sort

  1. Note how
    SharePoint is not in the list, we need to load the dlls!  Type the following command:


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

  1. You should
    get an output displaying the GAC, Version and Location information for the
    assembly
  2. Rerun the
    command to display the loaded assemblies, you should now see
    Microsoft.SharePoint loaded!

Exercise 2 – Create a PowerShell Profile

Purpose:
        Create
a PowerShell startup scripts

Result:           
A PowerShell script

Task 1 – Create the
script

  1. Open the C:WINDOWSsystem32windowspowershellv1.0
    directory
  2. Create a
    new file called Profile.ps1
  3. Open the
    new file and type the following into it:


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

  1. Close any
    open powershell prompts
  2. Open a new
    powershell prompt
  3. At startup
    you will get an error “…scripts is disabled on this systems”, we have to
    enable scripts to be run on the server!

Task 2 – Enable
Scripts

  1. Run the
    following command (you can also review the about_signing_help.txt file in
    the powershell install directory):


get-help about_signing

  1. Run the
    following command to get the execution policy:


get-executionpolicy

  1. Set  the execution policy to allow scripts to
    run:


set-executionpolicy unrestricted

  1. Close and
    reopen PowerShell, you should not get an error this time
  2. Run the
    following command:


[AppDomain]::CurrentDomain.GetAssemblies() | foreach-object {
split-path $_.Location -leaf } | sort

  1. You should
    see the SharePoint dll has been loaded!

Exercise 3 – Write a PowerShell Script (Enumerate Webs)

Purpose:
        Find
all the webs for a site collection

Result:           
A PowerShell script

Task 1 – Create the
script

  1. Open
    powershell, run the following:


$spsite = new-object Microsoft.SharePoint.SPSite("http://servername:100")

  1. NOTE: Be sure to replace servername
    with the name of your server
  2. NOTE: If you get an access denied
    error it likely means that you are logged in as spadmin, you can do two
    things:
    • Login as administrator on the server
      you are running powershell
    • Add spadmin as a site owner to the
      team site on port 100
  3. Run the
    following:


$spsite

  1. You will
    get a listing of all the properties that are available from the SPSite
    object! 
  2. One of the
    properties is a collection of all the webs in the site collection, run the
    following command:


$spsite.allwebs

  1. You will
    get an output all of the properties of the SPWeb object, too much
    information!
  2. Run the
    following command to select and sort specific properties:


$spsite.allwebs | select LastitemModifiedDate, URL, Created |
sort Created

  1. You can
    pipe the properties into other commands, so if you wanted to backup
    individual sites, you could do that!

Exercise 4 – Write a PowerShell Script (Create a Web)

Purpose:
        Create
A Web

Result:           
A PowerShell script

Task 1 – Create the
script

  1. Open
    powershell, run the following:


$spsite.allwebs.Add("sales", "Sales Site",
"Marketing And Sales", 1033, "STS#0", $true, $false)

  1. In a
    browser, open http://servername:100/sales
  2. You will
    see your new site!

Exercise 5 – Write a PowerShell Script (Create/Update an Item)

Purpose:
        Create/Update
an item

Result:           
A PowerShell script

Task 1 – Create the
script

  1. Open
    powershell, run the following commands:


$splist = $spsite.rootweb.lists["announcements"]
$splistitem = $splist.items[0]
$splistitem["Title"] = "a new title"
$splistitem.update()

  1. Open the http://servername:100 site, notice how
    the announcements list item has been updated!

Exercise 6 – Write a PowerShell Script (BackUp SharePoint)

Purpose:
        Learn
to use the SharePoint object model from PowerShell to backup SharePoint

Result:           
A PowerShell script to backup SharePoint

Task 1 – Create the
script

  1. Create a
    new directory called c:SharePointBackup
  2. Create a
    new script called BackUpSharePoint.ps1 in the c:scripts directory (create
    it if it doesn’t exist)
  3. Add C:scripts
    to your path
    • Click
      Start
    • Right
      click “My Computer”
    • Click
      the “Advanced” tab
    • Click
      the “Environment Variables” button
    • Click
      “Edit”
    • Add
      the following:


;c:scripts

    • Click
      Ok
    • Click
      Ok
    • Restart
      your PowerShell prompt
  1. Type the
    following into it:


$settings =
[Microsoft.SharePoint.Administration.Backup.SPBackupRestoreSettings]::GetBackupSettings("c:SharePointBackup",
"Full")

$backupId =
[Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::CreateBackupRestore($settings)

$obj = 
[Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::FindItems($backupId,
$settings.IndividualItem)[0]

[Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::SetActive($backupId)

[Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::Run($backupId,$obj)

 

  1. Open a PowerShell
    command prompt to c:scripts
    • If
      the script isn’t recognized, then you have to add c:scripts to your path
      environment variable
  2. Type
    backupsharepoint.ps1, type ENTER
  3. Open the
    c:sharepointbackups folder, notice you have some backups!

 

Creating a Custom Router for the Records Center

<!–[if !mso]>

Module #03: Custom
Router Lab #
03

 

 

Course:           Programming
Microsoft Office SharePoint Server

Estimated Time to Complete:  30 minutes

Objectives:

·        
Create a Custom
Router

Operating
Notes:
 

 

·        
None


Deliverables:

·        
None

 

Overview:         Learn
to extend the use of the Records Center!

Exercise 1 – Create A Custom Router

Purpose:
        Create
a new record router to route submitted documents!

Result:           
A new custom router

Task 1 – Create a
Class Library

  1. Create a new project
    • Click
      File->New->Project
    • Select “Class Library”
    • For name, type
      “MyCustomRouter”
    • For location, type “D:Lab
      Work”
    • Click “Ok”
  2. Add the following references:
    • Add a reference to
      Microsoft.SharePoint.dll
    • Add a reference to
      Microsoft.Office.Policy.dll

Task 2 – Create the
router

  1. In your project, rename
    Class1.cs to MyCustomRouter.cs
    • Right click, select
      “Rename”
    • Click “yes” to rename
      the class
  2. Add the following using statements:


using System.IO;

using Microsoft.SharePoint;

using Microsoft.Office.RecordsManagement;

using
Microsoft.Office.RecordsManagement.RecordsRepository;

using
Microsoft.Office.RecordsManagement.PolicyFeatures;

using Microsoft.Office.RecordsManagement.InformationPolicy;

 

 

  1. Implement the IRouter interface:


public class MyCustomRouter : IRouter

 

  1. Right click the IRouter text,
    select Implement Interface->Implement interface
  2. Update the OnSubmitFile
    method to the following:


try

            {

               
//Save it to disk

               
File.Create("C:\" + sourceUrl).Write(fileToSubmit, 0,
fileToSubmit.Length);

            }

           
catch (Exception ex)

            {

               
return RouterResult.RejectFile;

            }

 

           
return RouterResult.SuccessContinueProcessing;

 

 

Task 3 –Strong name
the project

  1. Right click the
    MyCustomRouter project, select “Properties”
  2. Click the “Signing” tab
  3. Click the “Sign the assembly”
    checkbox
  4. In the dropdown, select
    “<new>…”
  5. For key file name, type
    “MyCustomRouter”
  6. Uncheck the “Protect my key
    file…”
  7. Click “Ok”
  8. Compile the project, press F6
  9. Drag the D:Lab Work MyCustomRouterMyCustomRouter
    inDebug MyCustomRouter.dll file to the GAC (C:windowsassembly)

Task 4 – Create a
deployment application

  1. Create another project
    • In Visual Studio,
      click File->Add->New Project
    • Select “Windows
      Application”
    • For name, type
      “MyCustomRouterApp”
    • For location, type “D:Lab
      Work”

    • Click “Ok”
  1. Add some references
    • Add a reference to
      Microsoft.SharePoint.dll
    • Add a reference to
      Microsoft.Office.Policy.dll
  2. Add a button called
    “Register”, double click it
  3. Add the following using
    statements:


using Microsoft.SharePoint;

using Microsoft.Office.RecordsManagement;

using Microsoft.Office.RecordsManagement.RecordsRepository;

using
Microsoft.Office.RecordsManagement.InformationPolicy;

 

  1. In the button event handler,
    add the following:


using(SPSite site = new SPSite("http://servername:107"))

{

           
SPWeb web = site.RootWeb;

           
RecordSeriesCollection series = new RecordSeriesCollection(web);

           
series.AddRouter("My Router", "MyCustomRouter,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=[YOURPUBLICKEYTOKEN]", "MyCustomRouter.MyCustomRouter");

}

 

MessageBox.Show("Done!");

  1. NOTE: Be sure to replace servername and public key token!
  2. Set the MyCustomRouterApp to
    be the startup project
    • Right click the
      project, select “Set as startup project”
  3. Run the application, click
    the “Register” button

Task 4 – Test the
newly deployed router

  1. Open your Record Center Site
    (http://servername:107)
  2. Click “Record Routing”
  3. Edit the “Test” routing
    record

  1. For Router, select “My
    Router”

  1. Click “Ok”
  2. Open the RecordsManagementApp
    project from the last lab, submit the file again!
  3. Open your c: drive folder
    and notice the new file called “Custom Submit (no url)”, your new record
    router is working!

SharePoint Feature Deployment Map

I was doing some playing and decided to map out each level that each feature can be deployed too.  Check it out:

 

  Farm WebApplication Site Web
Control x x x x
Custom Action x x x x
Custom Action Group x x x x
Hide Custom Action x x x x
List Instance NO NO x x
List Template NO NO x x
Module NO NO x x
Receiver NO NO x x
Content Type NO NO x x
Field NO NO x NO
Workflow NO NO x x
ActivationDependency x – Follow Rules x – Follow Rules x – Follow Rules x – Follow Rules
FeatureSiteTemplateAssociation x x x NO

 

MCT Summit 2009!

Awesome news!  I have been asked to present at each of the MCT Summits in 2009!  I will be discussing the courseware library, where it has come from, where it is and where it is going!

 I plan to demo my CourseBuilder tool that we use to generate all our courses and dynamic courses!  The MCT Summit schedule is here:

 http://www.mctsummit2009.com/content/info.asp?Ccpsubsiteid=108&infoid=13

 The first stop is the Czech Republic, then back to my home town Seattle, then off to Asia!   I am looking forward to meeting all my fellow peers and educate everyone on how to be successful with the courseware library!

 Chris