Sharepoint client object model in Powershell

05/02/2013 11:30

#Get data from public Sharepoint Site using Client Object Model

# ================ Input parameters ==========================

$siteUrl = "https://server/sitecollection"

# ============== End of Input ================================

#Defining Load method for context, not accessible in Powershell
$csharp2 = @"

using Microsoft.SharePoint.Client;
namespace SharepointComLoad
{
    public class PSClientContext: ClientContext
    {
        public PSClientContext(string siteUrl)
            : base(siteUrl)
        {
        }
        // need a plain Load method here, the base method is some
        // kind of dynamic method which isn't supported in PowerShell.
        public void Load(ClientObject objectToLoad)
        {
            base.Load(objectToLoad);
        }
    }
}
"@

$assemblies = @("$location\Microsoft.SharePoint.Client.dll",
    "$location\Microsoft.SharePoint.Client.Runtime.dll",
    "System.Core")

$ErrorActionPreference = "Stop"

#Create ClientContext of our custom type
try
{
  $context = New-Object SharepointComLoad.PSClientContext($siteUrl)
}
catch [System.Management.Automation.PSArgumentException]
{
 Add-Type -TypeDefinition $csharp2 -ReferencedAssemblies $assemblies
 $context= New-Object SharepointComLoad.PSClientContext($siteUrl)
}

[Microsoft.SharePoint.Client.Web]$web = $context.Web
$context.Load($web)
$lists=$context.Web.Lists;
$context.Load($lists);
if($credentials -eq $null) {
 $credentials = Get-Credential
}
$context.Credentials = $credentials
$context.ExecuteQuery();

#Get web title
Write-Host "Web Title: " $web.Title

#Get Lists names
foreach($list in $lists)
{
 Write-Host "List Title: " $list.Title;
}

 

#Use CAML Query in Sharepoint object model to view list items

$camlQuery = new-object Microsoft.SharePoint.Client.CamlQuery;
$camlQuery.ViewXml = "<View>
<Query>
 <Where> 
      <Eq>   
       <FieldRef Name='Title' /> 
            <Value Type='Text'>My Subfolder Name</Value>
         </Eq>
       </Where>
 </Query>
</View>"

$listItems = $basiclist.GetItems($camlQuery);
$context.Load($listItems)
$context.ExecuteQuery();

foreach($item in $listItems)
{
 Write-Host "Title: " $item["Title"]
}