This is a first post of a series on how you can use PowerShell on the SharePoint object model and its web services. This post will give you an introduction on how to work with the SPSite and SPWeb objects.
Open a PowerShell command prompt. As we are going to explore the SharePoint object model, you need to have PowerShell installed on a machine where you installed SharePoint.
The first step is to load the SharePoint assembly:
[System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SharePoint”)
Instantiate an SPSite object:
$siteurl = "http://boske.litwareinc.com"
$mysite=new-object Microsoft.SharePoint.SPSite($siteurl)
Now you have a variable mysite, which contains an instance of type SPSite:
You can explore the content of the mysite variable by executing following command:
$mysite
Or to have the information listed per page:
$mysite | more
To list all the members of the site object:
$mysite | get-member | more
or the shorter notation:
$mysite | gm | more
You can also list only the properties of the site object:
$mysite | gm -membertype property | more
To view the content of a property of the site object:
$mysite.AllWebs
But this shows the whole content of all webs in the site collection. If you want to see only a few properties of each web, you could execute the following:
$mysite.AllWebs | format-table Url, ID, Name, AllUsers
or the shorter version
$mysite.AllWebs | ft Url, ID, Name, AllUsers
To get the webs ordered by the last time that the contents have been changed:
$mysite.AllWebs | sort LastItemModifiedDate | ft Url, ID, Name, LastItemModifiedDate
To loop through all webs of the site object and show the web Url and the Title of each list:
$mysite.AllWebs | foreach { $_.Lists | ft $_.Url, Title}
You should see something similar like this:
You can also execute a methods of objects. Just for fun, I will show you how to execute a CAML query:
$mytestweb = $mysite.OpenWeb("testsite")
$listguid = new-object System.Guid("f0715075-5159-43d7-99b7-3897824fbbff")
$productlist = $mytestweb.Lists[$listguid]
$query = new-object Microsoft.SharePoint.SPQuery();
$query.Query = "<Where><BeginsWith><FieldRef Name='ProductModel' /><Value Type='Text'>Mountain</Value></BeginsWith></Where><OrderBy><FieldRef Name='ProductModel' /></OrderBy>"
$productlist.GetItems($query) | ft Name
You can also view all static members of the SPSite class:
[Microsoft.SharePoint.SPSite] | get-member -static
If you want to execute a static member:
[Microsoft.SharePoint.SPSite]::MaxWebNameLength
I hope you liked the introduction on how to use PowerShell in combination with the SharePoint object model.