Wednesday, January 16, 2013

Powershell script to get SharePoint Workflow History List Items Count

The Powershell script below generates a CSV report that counts the number of SharePoint Workflow History List Items for all site collections and sub-sites within a web application. It also displays a progress bar as you loop through multiple sites/sub-sites and gives you real time processing information.

Copy the PowerShell script below and paste it in a notepad and save it with a .ps1 extension in any of your local drives.
=====================================================================

param
(
   $url
)

Add-PSSnapin Microsoft.SharePoint.PowerShell -ea SilentlyContinue

## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")

if(![string]::IsNullOrEmpty($url))
{
        try
        {
        $webAppURI = New-Object Uri($url)
        $spwebapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($webAppURI)
        }
        catch [System.Exception]
        {
        Write-Warning "Web Application could not be found on the server. Check Webapplication URL before executing this script."
        exit;
        }
       
        $spbasetypegenericlist=[Microsoft.SharePoint.SPBaseType]::GenericList

        $output = @()
        $heading = "Site Collection URL; Site URL; Site Name; List Title; List URL; List Item Count"
        $filename = "." + $spwebapp.Name + "-" + $(Get-Date -Format MM-dd-yyyy-HH-mm) + ".csv"
       
        #Write CSV file Headers
        Out-File -FilePath $filename -InputObject $heading;
       
         #Log file name
        $logName = "." + $spwebapp.Name + "-" + $(Get-Date -Format MM-dd-yyyy-HH-mm) + ".log"
        #Write-Output "Site Collection URL; Site URL; Site Name; List Title; List URL; List Item Count" | Out-File $logname
     
        foreach ($spsite in $spwebapp.Sites)
        {
            try
             {
                #Progress Bar
                $sitesProcessed = 0;
                $siteMax = $spsite.AllWebs.Count;

                foreach ($spweb in $spsite.AllWebs)
            {
                    #Display Progress Bar on Site Completion
                    $sitesProcessed++;
                    $percent = ($sitesProcessed/$siteMax) * 100
                    Write-Progress -Activity "Looping through Sites" -PercentComplete $percent -CurrentOperation "$sitesProcessed / $siteMax" -Status "$spweb.Title"

                    try
                    {
                        $spgenericlists = $spweb.getlistsoftype($spbasetypegenericlist)
                   
                        if ($spgenericlists -ne $null)
                        {
                    foreach ($list in $spgenericlists)
                    {
                    if($list -ne $null)
                                {
                                    if ($list.basetemplate -eq "WorkflowHistory")
                        {
                        $output += $($spsite.Url + ";" + $spweb.Url + ";" + $spweb.Title  + ";" + $list.Title  + ";" + $list.DefaultViewUrl + ";" + $list.ItemCount)
                        }
                                }
                    }
                        }
                    }
                    catch
                    {
                        Write-Host "Exception thrown at" $spsite.Url $spweb.Url $list.Title
                        Write-Error ("Exception thrown at:" + $_)
                       
                        #Write Exception to Log file
                        Write-Output "Exception thrown at" $spweb.Url $list.Title $list.DefaultViewUrl $_ | Out-File $logname -append
                    }
                   
            $spweb.Dispose()
                 }
              }
              catch [System.Exception]
              {
                  Write-Host "Exception at" $spsite.Url $spweb.Url $list.Title
                  Write-Warning ("Exception thrown at: " + $_)
                 
                  #Write Exception to Log file
                  Write-Output "Exception thrown at" $spweb.Url $list.Title $list.DefaultViewUrl $_ | Out-File $logname -append
              }
              finally
              {
                  $spsite.Dispose()
              }
        }
       
        if($output -ne $null)
        {
            $output | Out-File $filename -Append
            Write-Host "Output file has been created successfully."
           
            #Write-Output $output | Out-File $logname -append
        }
        else
        {
            Write-Warning "Error creating the CSV file."
           
            #Write Exception to Log file
            Write-Output "Error creating the CSV file" | Out-File $logname -append
            exit
        }
}
else
{
    Write-Warning "Web Application URL parameter cannot be blank."
    Write-Warning("Use Syntax: .GetAllWFHistoryItemCount.ps1 -url <Your Web App URL>")
exit
}

Write-Host "Finished"

==============================================================================

Automate the above .ps1 script as a batch utility, Copy and paste code below and save it with a .bat file extension, change the script file name and enter your web application URL, in the highlighted yellow section, save and run the automated batch file.

cd /d %~dp0
powershell -noexit -file ".GetWorkflowHistoryListItem.ps1-url "https://sharepointfix.com "%CD%"
pause

Run the batch file and import the CSV file generated into an Excel sheet. Delimit the columns with a "*" and then check the Count of Workflow History List Items for each of your Site Collection and Sub sites within.

Monday, October 29, 2012

Introduction to SharePoint 2013 App Model - A Primer

SharePoint 2013 introduces the new App Model that adds another dimension to the kinds of solutions you can build on the SharePoint technology platform in addition to Full Trust Solutions and Sandboxed solutions.

Lets take a deep dive on the App Model and understand the fundamental building blocks. 

I. SharePoint 2013 App Model Highlights:
  1. SharePoint applications no longer live in SharePoint
  2. Custom code executes in the client, cloud or on-prem
  3. Apps are granted permissions to SharePoint via OAuth
  4. Apps communicate with SharePoint via REST / CSOM
  5. Acquire apps via centralized Marketplace, Corporate Marketplace, Public Marketplace (via submission process)
  6. APIs for manual deployment
  7. Everything in a SharePoint site is an app: Contact form, Travel request, Shared Documents library, Contacts list
  8. Apps for SharePoint mimics Facebook Apps to an extent.
II. SharePoint 2013 App Model Benefits:
  1. No custom code on the SharePoint server
  2. Easier to upgrade to future versions of SharePoint
  3. Works in hosted environments w/o limitations
  4. Reduces the ramp-up time for those building apps
  5. Don’t need to know/be as familiar with SharePoint “-isms”
  6. Leverage hosting platform features in new apps
  7. Enables taking SharePoint apps to different levels – further than what can be done with farm / sandbox solutions
  8. Isolation – private vs. public clouds
III. SharePoint 2013 Application Architecture: The diagram below talks about the SP 2013 Application Architecture and its components.

REST / CSOM - are the programmatic approaches available to access SP 2013 data from Apps.
Remote Event Receivers - To handle events in an app for SharePoint remotely, you create remote event receivers and app event receivers.
BCS - Apps can perform CRUD operations on external data store using ODATA by leveraging External Content Types and External Lists.

IV. SharePoint 2013 App URL:
V. SharePoint 2013 Application Comparison Chart: Lets see what programming options we have while creating Apps for SharePoint.
VI. Different kinds of Apps for SharePoint 2013:  Here are 3 different kinds architecture approaches available for creating SharePoint 2013 Apps.
 
 1. SharePoint-Hosted App:
  •     SharePoint hosted apps wholly reside in SharePoint
  •     Uses SharePoint artifacts (lists/libraries)
  •     Business logic executes or on the client
  •     HTML5
  •     JavaScript using CSOM or REST API's
 2. Cloud based Apps:
  •     Cloud hosted apps primarily execute outside of SharePoint
  •     May use SharePoint artifacts (lists/libraries)
  •     Communicate via CSOM / REST
  •     Granted permission to SharePoint via OAuth
  •     Business logic lives & executes outside of SharePoint
  •     On-Premise hosted web application
  •     Windows Azure
  •     3rd party host
  •     Managed CSOM (Client Side Object Model) can be adopted as a programming model for both     these kinds of Apps.   
  •     Within cloud based apps, we have a further bifurcation between:  
  •     Provider-Hosted Apps- Apps developed/maintained on Premises or a Private Cloud.  
  •     Auto-Hosted Apps - Apps provisioned using Windows Azure Auto-Hosting. SharePoint deploys ASP.NET application & SQL Azure DB to Azure automatically when SharePoint app is installed.
VII. SharePoint 2013 Application UX (User Experience):

VIII. SharePoint 2013 Application Scopes:
i. Web scope - By default all SharePoint 2013 SharePoint apps are scoped to Web.
ii. Tenant scope - Cloud based apps can have their Apps as tenant scoped. For e.g.: Apps hosted on Office 365 can have a Tenant scope for privacy and security. Not Applicable to SharePoint Hosted Apps.

IX. SharePoint 2013 App Hosting Options: Cloud v/s SharePoint
 
 X. SharePoint 2013 Application Isolation:
  • When apps are provisioned, new SPWeb (AppWeb) created within hosting SPWeb
  • Each app resides within it’s own SPWeb for isolation
  • Special DNS address configured by administrators
  • App SPWeb’s live in separate domain (DNS)
  • Each App hosted on it’s own unique URL because:
  • Blocks XSS: isolation to special SPWeb under special domain blocks cross site scripting
  • Enforces App Permissions: apps communicate with sites via CSOM /API & must be granted to do so
XI. Obtaining SharePoint 2013 Applications:
 Applications can be acquired multiple ways:
  • Public Marketplace
  • Similar Windows Phone Marketplace
Subject to submission process & approval
  • App Catalog
  • Apps developed internally
Apps acquired and approved for internal use
  • Custom Deployment Process
  • Developers can use remote / local SharePoint & Windows Azure APIs to deploy apps with custom code. These APIs are restricted to the developer site for tooling scenarios

Thursday, September 13, 2012

Powershell script to Export and Import Managed Metadata Termstore across SharePoint farms while still retaining its GUIDs

While migrating your site collections from one farm to the other, Managed Metadata termsets being used and stored in lists and libraries for various site collections would reference to the GUID’s of the original managed metadata term store. The site columns themselves, would reference the GUID of the term sets of the source managed metadata service. Hence, it becomes difficult to migrate the various site collections to the new farm. In this situation, we run the risk of making the existing managed metadata columns being orphaned for the source site collection to be migrated.

Below mentioned PowerShell script Exports and Imports Managed Metadata termstore still retaining its GUID's (sspId's- used internally by the Termstore) and referred by Managed metadata columns in list/library.

#Export Managed Metadata Taxonomy Name

$managedMetadataAppSource = “4a867ce5-d9ee-4051-8e73-c5eca4158bcd”; #this sets the exporting MMS ID
$mmSourceProxy = Get-SPServiceApplicationProxy | ?{$_.TypeName -eq "Managed Metadata Service Connection"};
Export-SPMetadataWebServicePartitionData -Identity $managedMetadataAppSource -ServiceProxy $mmSourceProxy -Path "C:\ExportManagedMetadata\locationexportfile.bak";

#Import Managed Metadata Taxonomy Name

$managedMetadataAppTarget = "d045d3ce-e947-4465-b039-0dfbbe24fb22"   #this sets the importing MMS ID
$mmTargetProxy = Get-SPServiceApplicationProxy | ?{$_.TypeName -eq "Managed Metadata Service Connection"};
Import-SPMetadataWebServicePartitionData -Identity $managedMetadataAppTarget -ServiceProxy $mmTargetProxy -Path "C:\ImportManagedMetadata\locationexportfile.bak" -OverwriteExisting;

Friday, September 7, 2012

Powershell Script to query and export Workflow History List Items across a Site Collection using CrossListQueryInfo in a .csv file

This Power Shell script queries across a given Site Collection using CrossListQueryInfo and CrossListQueryCache objects available in SharePoint 2010 OM. The script also generates a CSV file report of all Workflow History List items across the given site collection.

Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")
   
    $SiteCollUrl = "https://sharepointfix.com/sites/crosslistquerycache"
 
    $site = new-object Microsoft.SharePoint.SPSite($SiteCollUrl)
    $web = $site.OpenWeb()
   
    try
       {
        #Specify your CAML query here
        $caml = "" #You can specify your <Where/> clause here
        $lists= "<Lists ServerTemplate='140' Hidden='True'/>"
        $viewFields = "" #You can specify your <ViewFields/> here
        $webs = "<Webs Scope='SiteCollection' />"
        $queryInfo = new-object Microsoft.SharePoint.Publishing.CrossListQueryInfo
        $queryInfo.Webs = $webs
        $queryInfo.Lists = $lists
        $queryInfo.ViewFields = $viewFields
        $queryInfo.Query =$caml
        $crossListCache =  new-object Microsoft.SharePoint.Publishing.CrossListQueryCache –ArgumentList $queryInfo
        $allow= "TRUE"
        $results = $crossListCache.GetSiteDataResults($web, $allow)
        Write-Host "There are $($results.Data.Rows.Count) items."
        $results.Data | Export-Csv -Path "F:\WorkflowHistoryListItemReport.csv" -NoTypeInformation -Force       
       }
    catch
    {
        "Error encountered:" | Out-Default
        $_.Exception | Write-Error
    }
    finally
    {
        $web.Dispose()
        $site.Dispose()
    }
   
Remove-PsSnapin Microsoft.SharePoint.PowerShell
Write-Host "Finished"

Monday, June 18, 2012

Powershell script to get Site Collection Pages and List Items count using SPSiteDataQuery object

This PowerShell script queries a given Site Collection and returns all its Pages and List Item count recursively using SPSiteDataQuery object model.

Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")

# CHANGE THE FOLLOWING LINE TO POINT TO THE DESIRED PORTAL SITE COLLECTION
$web = Get-SPWeb "http://sharepointfix/sites/spsitedataquery"

if($web -ne $null)

    # Adding fields to the view
    $viewFields = New-Object System.Collections.Specialized.StringCollection
    $viewFields.Add(“Title”)
    $viewFields.Add(“Name”)

    # Construct the query object for publishing pages
    $queryPages = New-Object Microsoft.SharePoint.SPSiteDataQuery
    $queryPages.Lists = "<Lists ServerTemplate=""850""/>"

    #Specify your clause here
    $queryPages.Query = ""
    $queryPages.RowLimit = 1000000
    $queryPages.ViewFields = $viewFields
    $queryPages.Webs = "<Webs Scope=""Recursive""/>"
   
    # Construct the query object for list items
    $queryItems = New-Object Microsoft.SharePoint.SPSiteDataQuery
    $queryItems.Lists = "<Lists ServerTemplate=""100""/>"

    #Specify your clause here
    $queryItems.Query = ""
    $queryItems.RowLimit = 1000000
    $queryItems.ViewFields = $viewFields
    $queryItems.Webs = "<Webs Scope=""Recursive""/>"
   
    # Execute both queries and display the count of the number of pages and items
    $pagesData = $web.GetSiteData($queryPages)
    $itemsData = $web.GetSiteData($queryItems)
    Write-Host "There are $($pagesData.Rows.Count) pages and $($itemsData.Rows.Count) items."
   
    $web.Dispose()
}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

Write-Host "Finished"

Benefits of SPSiteDataQuery over SPQuery is that SPSiteDataQuery queries the whole site collection including all its subsites recursively and brings back the desired data.