Home Page Link
  Skip Navigation Links
ZA SharePointers
Information Worker > Blogs > ZA SharePointers > Posts > SharePoint and PowerShell
SharePoint and PowerShell

We had a community meeting on the 19th of June 2008 and I did a presentation to give an overview on why and how to use PowerShell in a SharePoint environment. This blog is partly to post the commands that I used in the presentation and partly to explain how to other stuff with PowerShell that I was asked about in and after the Presentation.

The demo was about provisioning different lists in a site in SharePoint. The first step in connecting to SharePoint is to load the necessary .Net library. This can be done with the following command:

[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")

I went through the following commands in the demo. I added comments in to explain what is happening.

$site = New-Object Microsoft.SharePoint.SPSite("http://adbmoss")

# Connect to the site collection http://adbmoss and store the object in the $site variable

$site | get-member

# Display all the properties and methods for the object in $site

$site.set_readonly($True)

# Set the site collection to read only. No updates are allowed

$site.set_readonly($False)

# Set the site collection back to read-write

$root = $site.rootweb

# Connect to the root site in the site collection and store the object in $root

$root | get-member

# Display all the properties and methods for the object in $root

$root.lists | format-table -property title, author

# Display title and authors for all the lists in the root site

$root.lists | ?{$_.iscatalog -eq $null} | format-table -property title, author

# Filter the lists to show only the user lists. The $_ symbol refers to the object in the piple line. The ? symbol is an alias for the where-object commandlet.

$root.listtemplates | format-table -property name

# Show all the available list templates for the root web

$TempCal=$root.listtemplates["Calendar"]

# Store the Calendar template in a variable $TempCal

$root.lists.add("Events","Company Events", $tempCal)

# Create a list called “Events” with Description “Company Events” on the calendar template

import-csv dept.csv | %{$root.lists.add($_.Dept, $_.Descr,$root.listtemplates[$_.Temp])}

# Create a new list for ever line in a CSV file where the name for the list is saved in the Dept column of the file, the description is in the Descr column, and the type of list to create is in the Temp column. First check that the lists are correctly created before you continue. The % symbol is an alias for the foreach-object commandlet and places each instance of the collection in the pipeline one after the other.

import-csv dept.csv | %{$root.lists[$_.Dept].delete()}

# Use the CSV file again to delete all the create lists again.

You can get the sample CSV file here.

In the presentation one of the delegates asked if PowerShell can be used to provision additional columns in a custom list as well. The answer is yes, and the following commands show how to accomplish that.

[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")

# Load SharePoint library

$site = New-Object Microsoft.SharePoint.SPSite("http://adbmoss")

# Connect to the site collection http://adbmoss and store the object in the $site variable

$root = $site.rootweb

# Connect to the root site in the site collection and store the object in $root

$root.lists.add("CTest","Custom Test",$root.listtemplates["Custom List"])

# Create a new list called “CTest” from the template “Custom List”

$list = $root.lists["CTest"]

# Set a variable $list to the custom list that was just created.

$list.fields.add("T1","Text",0)

# Create a new field of type Single Line Text with the name of “T1”. The field is not required (last parameter)

After the presentation I had a question if PowerShell can be used to update metadata in a document library. The scenario was that the documents were already in the library and they had a spreadsheet with the id number of the document and some additional meta-information. This can also be done in PowerShell. The first step is to save the spreadsheet in CSV format or any other format that PowerShell can easily import. The following code shows how to go about importing the metadata.

[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")

# Load SharePoint library

$site = New-Object Microsoft.SharePoint.SPSite("http://adbmoss")

# Connect to the site collection http://adbmoss and store the object in the $site variable

$root = $site.rootweb

# Connect to the root site in the site collection and store the object in $root

$docs = $root.lists["Shared Documents"]

# Store the Shared Documents document library in a variable $Docs

import-csv DocProps.CSV | %{$item = $Docs.items[$_.id]; $item["Title"] = $_.Title; $Item["Group"] = $_.group; $Item.Update()}

# Loop through the csv file and update the properties

The last line of this script is a bit cryptic. I will break it out in the next few lines to explain the detail of how it works. The following lines might not work if you copy and paste it.

import-csv DocProps.CSV # Import the data from the DocProps CSV file

    | # Pipe the results to the group

         %{ # For each (%) line in the csv file do begin ({)

                $item = $Docs.items[$_.id]; # set the variable $item to the entry in the list where the id corresponds to the id column in the file. The semicolon (;) indicates the separate command is to follow

                $item["Title"] = $_.Title; # set the title of $item to Title in the file

                $Item["Group"] = $_.group; # set the Group metadata property to the group Column in the file

                $Item.Update() # update the entry $item in the list

              } # End (}) the loop

You can get the sample CSV file here.

As you can see the one liner in PowerShell can be very complex and powerful. Just keep your head.

You can download PowerShell from the Microsoft download site. There is a few download links:

PowerShell 1.0 English for Windows 2003

PowerShell 1.0 English for Windows 2003 x64

PowerShell 1.0 Graphical Help File

Happy Scripting

Comments

Wow, this is great!!!

This is really cool. Thanks Andre for sharing this information.
Michael O'Donovan at 6/20/2008 8:52 AM

Adding "Choice" columns to a custom List/Library

How can you add a choice column to a custom List and then add the choices with powershell?  I have gotten it to create a choice column by replacing "Text" with "Choice" but am not able to add choices to it...

$list.fields["NameOfList"].choices.add("Choice1") does not seem to work...

Any ideas?  Thanks
at 11/19/2008 6:16 PM

RE: Adding "Choice" columns to a custom List/Library

You can use one of the overloaded methods of SPFieldCollection.Add (see MSDN: http://msdn.microsoft.com/en-us/library/ms477246.aspx).

This overload accepts a StringCollection parameter that contains the choices you're adding. Just remember to reference the System assembly in your PowerShell script.

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

$siteUrl = "http://moss-test/"
$spSite = New-Object Microsoft.SharePoint.SPSite($siteurl)
$spWeb = $spSite.RootWeb

# add new list based on Custom List template
$listId = $spWeb.Lists.Add("My List", "", $spWeb.ListTemplates["Custom List"])
$spList = $spWeb.Lists[$listId]

$choices = New-Object System.Collections.Specialized.StringCollection
$choices.Add("One")
$choices.Add("Two")
$choices.Add("Three")

$fieldName = $spList.Fields.Add("My Choice", [Microsoft.SharePoint.SPFieldType]::Choice, $FALSE, $FALSE, $choices)
$spList.Update()
Dario Mratovich at 11/20/2008 11:53 AM

Creating wiki pages using Powershell

I have wiki title and wiki content in a csv.Please let me know how to create wiki pages with the contents in csv using Powershell
at 8/28/2009 4:05 PM

RSS Feed RSS 2.0 Feed





Feedback