Quantcast
Channel: SharePoint Diary
Viewing all 1058 articles
Browse latest View live

Customized Master Pages Report for All SharePoint Sites

$
0
0
Today, wanted to audit customized Master pages which are deviating from our corporate Branding in my Team Sites environment.

Generated the report for customized master pages with help of PowerShell.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get all site collections of provided web app
$SiteCollections = Get-SPWebApplication "http://sharepoint.crescent.com" | Get-SPSite -Limit All

#Loop through all site collections
   foreach($Site in $SiteCollections)
    {
        #Loop throuh all Sub Sites
       foreach($Web in $Site.AllWebs)
       {    
        #Get the Master Page
        $MasterPage = $Web.GetFile($Web.MasterUrl)
     #Check the Customization Status
        if ($MasterPage.CustomizedPageStatus -eq "Customized")
     {
             $MasterPage.Name  +" : " +$Web.Url  
     }
       }

    }

If you want to use it in MOSS 2007, use these two lines of code to get a specific web application:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$webApp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup("http://sharepoint.crescent.com")

Here is the One Liner:
Get-SPWebApplication "http://sharepoint.crescent.com" | Get-SPSite -Limit All | Get-SPWeb -Limit All | Select Title, URL, MasterUrl

Frankly, SharePoint Designer is a tool inducing people to get their site's look and feel just as they want. I blame you SharePoint Designer for that. I've no options left other than locking you down from ordinary users.

Get SharePoint Library Size with PowerShell

$
0
0
SharePoint 2010 document library sizes can be easily retrieved via Storage metrics: Site Actions>> Site Settings >> Storage Metrics if you have SP1 installed.
sharepoint get document library size

You can get SharePoint library size, ONLY when you have Quotas applied to the site collection. otherwise, you get "The storage space allocation page cannot be used for sites that do not have a storage quota defined." error message in MOSS 2007.
The storage space allocation page cannot be used for sites that do not have a storage quota defined

How to find a particular document library's size in SharePoint programmatically?
Lets see the PowerShell approaches to find SharePoint 2007/SharePoint 2010 document library size, picture library size or for any other libraries.

Approach 1: Using StorageManagementInformation API:
It retrieves storage management information about the site collection. More info on StorageManagementInformation , It takes these parameters:

1. ltVar: Which object
        List = 1
        DocumentLibrary = 2
        Document = 3
2. sordVar: sort order
        Increasing = 0×10
        Decreasing = 0×11
3. soVar: Sort based on size or date
        Size=0
        Date = 1
4. nMaxResults: number of results to return

Lets get the size of the "Shared Documents" Library with PowerShell:
#SharePoint library size report
#Get the Site collection
$Site = Get-SPsite "http://sharepoint.crescent.com"

#Returns a DataTable similar to "Storage Management Page" in Site settings
$DataTable = $Site.StorageManagementInformation(2,0x11,0,0)

#Loop through the Rows and Fetch the row matching "Shared Documents" in subsite "team"
 foreach($Row in $DataTable.Rows)
{
    if ($Row.Title -eq "Shared Documents" -and $Row.Directory -eq "team")
        {
            $LibrarySize = [Math]::Round(($Row.Size/1MB),2)
            Write-Host $LibrarySize "MB"
        }
} 

You can retrieve Top 10 large libraries based on their size as:
#Get the Site collection
$Site = Get-SPsite "http://sharepoint.crescent.com"

#Returns a DataTable similar to "Storage Management Page" in Site settings
$DataTable = $Site.StorageManagementInformation(2,0x11,0,10)

$DataTable | Select Title, ItemCount, Size, Directory | Format-Table
and the output:
However MSDN says this API is obsolete. So lets try with an alternate approach. Found this Article in MSDN on getting the storage information through object model.

Approach 2: Iterate through each document and its versions stored in the library to calculate the library size:
Lets use PowerShell to iterate each folder & sub-folder of a particular document library. This script can be used in MOSS 2007 or SharePoint 2010 get library size.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

# Function to calculate Library size
Function GetLibrarySize($Folder)
{
    $FolderSize = 0
    foreach ($File in $Folder.Files)
    {
        #Get File Size
        $FolderSize += $File.TotalLength;

        #Get the Versions Size
        foreach ($FileVersion in $File.Versions)
        {
            $FolderSize += $FileVersion.Size
        }
    }

      #Get Files in Sub Folders
        foreach ($SubFolder in $Folder.SubFolders)
        {
           if($SubFolder.Name -ne "Forms") #Leave "Forms" Folder which has List default Aspx Pages.
             {
                 $FolderSize += GetLibrarySize($SubFolder)
             }
        }

       return [Math]::Round(($FolderSize/1MB),2)
}

$Web = Get-SPWeb "http://sharepoint.crescent.com/team/"

#Get the Library's Root Folder
$Library =  $Web.Lists["Shared Documents"].RootFolder

#Call the function to Calculate Size
$LibrarySize=GetLibrarySize($Library)

Write-Host "Library Size:" $LibrarySize "MB"

User's Account Name Changed in Active Directory. How to Sync it in SharePoint?

$
0
0
We had a user account in Active Directory: EU\susanapi. Later there was a change in User name. It become: EU\suzanapi. But even after several user profile imports, the old user name: EU\susanapi was still showing up in SharePoint, and SharePoint treated the new user account as a separate account.

What is the Fix?
Unfortunately, Sharepoint doesn't understand this change automatically. We need to make it understand by giving instruction via STSADM command.

When user's Account Name (or Login Name: Domain\User) renamed in Active Directory, you have to use stsadm -o migrateuser command to associate the new AD account with an existing SharePoint profile.

stsadm -o migrateuser -oldlogin EU\susanapi -newlogin EU\suzanapi -ignoresidhistory

PowerShell cmdlet to migrate user: Move-SPUser –Identity "DOMAIN\OldUserName" –NewAlias "Domain\NewUserName"

Before the Fix:

After the Fix:
I had to do the same thing When users left the company, their accounts are deleted in AD (But their profiles are not deleted in SharePoint). After some time they came back! New AD-Account created and I just used the MigrateUser command to associate the new account with their existing user profile.

By this, All their profile Data, Security Settings, Tasks assigned and My Site are associated back with the users.  This procedure also applies when we migrate users from other domains. (or during domain Renames!) KB: http://support.microsoft.com/kb/953131

BTW, If its for any other properties like Display Name, First Name, Last Name, etc, Profile imports should sync it back with SharePoint. If you need the change urgently either you can trigger the Profile import on-demand or you can update the user property by SPUser.Property=something or with PowerShell Set-SPUser.

MOSS 2007 List Toolbar in SharePoint 2010

$
0
0
After migrating from MOSS 2007 to SharePoint 2010, some users still face difficulty with SharePoint 2010 interface, especially ribbon. What they are asking for is: List toolbar is missing! We need MOSS 2007 style list view toolbar!!

As SharePoint 2010 list toolbar integrated with ribbon, SharePoint doesn't show list toolbar separately, by default.
sharepoint 2010 list toolbar

However, we can just tweak this settings to show SharePoint 2010 list view toolbar as in SharePoint 2007. Here is how:


Go to Site Actions>> Edit Page>> Modify List View Web Part
sharepoint 2010 list view show toolbar

Set list view toolbar type  from "Full Toolbar" to "Show Toolbar"
sharepoint 2010 list view toolbar type

That's all. See the toolbar appears on list!

SharePoint Versioning Manager - Control Versioning Settings & Clean Up Old Versions

$
0
0
We have document libraries with unlimited versioning enabled for years. As part of regular auditing Version History Size Report for Entire SharePoint Web Application , found many documents have more than 100 versions!  In order to free up more database storage space and for better performance, We understand that we'll have to disable or limit versions.

Although, versions are very useful to track changes, each of the versions is a copy of the document and takes up a disk space (Till SharePoint 2010, BTW). As per Microsoft design changing versioning limits will not delete existing minor/major versions of the file until we update it.

Its a best practice to limit versions. You can Navigate to Document Library Settings>> Version Settings>> and set versioning limits, set versioning ON/OFF in SharePoint versioning settings page. But this will not have any effect on existing documents until you make edits on the document and update. (You can Check-out and check-in them back as a Shortcut). Also its not possible to get into each document library and set these settings manually, isn't it? As there were thousands of files in the document library I would like to programmatically approach the change to simply get rid of the old versions across the site and regain space.

PowerShell can Set Versioning Limits and Cleanup Old Versions:
All of these issues can resolved with a powershell script which does clean up of old versions in SharePoint library by looping through all the site collections, webs, lists and items. From each item it checks the versions and delete. Take a look at my post: Limit and Cleanup Versioning in SharePoint with PowerShell

However, not all guys are good at PowerShell scripting (You must be good at PowerShell, SharePoint Admins!) and obviously its easy to make disaster if you are novice! So, would like to have a GUI based SharePoint utility to fix versioning of document libraries.

SharePoint Versioning Manager Utility to Set Limits and Cleanup Old Versions
I've created a SharePoint tool using C# object model, which gives the functionality to manage document versions and  programmatically remove extraneous versions either for a selected list or library or of all lists and libraries in a SharePoint site. It takes parameters such as:
  • Site collection URL, Site
  • List/Library (or All List & Libraries)
  • Define Version limits (No. of major versions / No. of minor versions to keep)
  • Turn OFF/Turn ON versioning for selected or all lists/libraries.
and perform desired operations. Here are some screen shots of SharePoint Versioning Manager in action.
This utility is built on SharePoint server object model and must be running from SharePoint Web Front End Servers! Not from your desktop!!
Get Versioning Analysis of all document libraries and lists:
Tool to Analyze sharepoint versioning Settings
Analyze Versionings of a Selected Library:Reduce sharepoint versioning to get storage space
Set Versioning Limit and Cleanup for a Selected Library:
SharePoint Versioning Manager - Control and Clean Up Old Versions Set the versioning limits either for selected list/library or for entire site.
Tool to Trim and Cleanup SharePoint Versions
 In a Project collaboration environment, with this utility, We had a doc library setup with versioning 5 major and 5 minor. we recovered about to 28 GB of free space!

Download SharePoint Versioning Manager from CodePlex

SharePoint doesn't enable versioning by default!

As always, I see there are room for enhancements to the tool, will update and release a new version as and when time allows!

Audit Specific User Permissions in SharePoint 2007 with PowerShell

$
0
0
In continuation with my earlier post: SharePoint Permission Report: Check Access Rights for a Specific User, got few requests to make the PowerShell script compatible with MOSS 2007. Hence, I'm posting the code here.

It checks the following areas of SharePoint and generates a Log file as in the below screen:
  • Farm Administrator's Group
  • Central Administration Web Application Policies
  • Site Collection Administrators 
  • Scans the all Site collections and Sub-sites with Unique Permissions
  • Scans all Lists and Libraries with unique permissions
  • Scans all Groups which has permissions on sites and Lists

PowerShell Script to Check Access Rights for a Particular user all over SharePoint:

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


#Get All Web Applications
Function global:Get-SPWebApplication($WebAppURL)
{  
 if($WebAppURL -eq $null)  #Get All Web Applications
    {
  $Farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
  $websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
  $WebApps = @()
  foreach ($websvc in $websvcs) {
      foreach ($WebApp in $websvc.WebApplications) {
          $WebApps = $WebApps + $WebApp 
      }
  }
  return $WebApps
 }
 else #Get Web Application for given URL
 {
  return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
 }
}

Function global:Get-SPSite($url)
{
 if($url -ne $null)
    {
    return New-Object Microsoft.SharePoint.SPSite($url)
 }
}
 
Function global:Get-SPWeb($url)
{
  $site= Get-SPSite($url)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
      
            }
    return $web
}

Function GetUserAccessReport($WebAppURL, $SearchUser)
{
 #Get All Site Collections of the WebApp
 $SiteCollections = Get-SPWebApplication($WebAppURL)
 $SiteCollections= $SiteCollections.Sites
 

 #Write CSV- TAB Separated File) Header
 "URL `t Site/List `t Title `t PermissionType `t Permissions" | out-file UserAccessReport.csv

  #Check Whether the Search Users is a Farm Administrator
        $ca= [Microsoft.SharePoint.Administration.SPAdministrationWebApplication]::Local.Sites[0].RootWeb
        #Get Central Admin
    $AdminSite = Get-SPWeb($ca.URL)
    $AdminGroupName = $AdminSite.AssociatedOwnerGroup.Name

    $FarmAdminGroup = $AdminSite.SiteGroups[$AdminGroupName]

     foreach ($user in $FarmAdminGroup.users)
      {
       if($user.LoginName -eq $SearchUser)
    {
     "$($AdminSite.URL) `t Farm `t $($AdminSite.Title)`t Farm Administrator `t Farm Administrator" | Out-File UserAccessReport.csv -Append
    }      
      }

 #Check Web Application Policies
 $WebApp= Get-SPWebApplication $WebAppURL

 foreach ($Policy in $WebApp.Policies) 
   {
   #Check if the search users is member of the group
  if($Policy.UserName -eq $SearchUser)
     {
    #Write-Host $Policy.UserName
     $PolicyRoles=@()
     foreach($Role in $Policy.PolicyRoleBindings)
    {
     $PolicyRoles+= $Role.Name +";"
    }
    #Write-Host "Permissions: " $PolicyRoles
    
    "$($WebAppURL) `t Web Application `t $($AdminSite.Title)`t  Web Application Policy `t $($PolicyRoles)" | Out-File UserAccessReport.csv -Append
   }
   }
  
  
  #Loop through all site collections
   foreach($Site in $SiteCollections) 
    {
   #Check Whether the Search User is a Site Collection Administrator
   foreach($SiteCollAdmin in $Site.RootWeb.SiteAdministrators)
       {
    if($SiteCollAdmin.LoginName -eq $SearchUser)
   {
    "$($Site.RootWeb.Url) `t Site `t $($Site.RootWeb.Title)`t Site Collection Administrator `t Site Collection Administrator" | Out-File UserAccessReport.csv -Append
   }      
  }
  
    #Loop throuh all Sub Sites
       foreach($Web in $Site.AllWebs) 
       { 
   if($Web.HasUniqueRoleAssignments -eq $True)
             {
          #Get all the users granted permissions to the list
             foreach($WebRoleAssignment in $Web.RoleAssignments ) 
                 { 
                   #Is it a User Account?
      if($WebRoleAssignment.Member.userlogin)    
       {
          #Is the current user is the user we search for?
          if($WebRoleAssignment.Member.LoginName -eq $SearchUser)
         {
          #Write-Host  $SearchUser has direct permissions to site $Web.Url
          #Get the Permissions assigned to user
           $WebUserPermissions=@()
             foreach ($RoleDefinition  in $WebRoleAssignment.RoleDefinitionBindings)
             {
                             $WebUserPermissions += $RoleDefinition.Name +";"
                            }
          #write-host "with these permissions: " $WebUserPermissions
          #Send the Data to Log file
          "$($Web.Url) `t Site `t $($Web.Title)`t Direct Permission `t $($WebUserPermissions)" | Out-File UserAccessReport.csv -Append
         }
       }
     #Its a SharePoint Group, So search inside the group and check if the user is member of that group
     else  
      {
                        foreach($user in $WebRoleAssignment.member.users)
                            {
           #Check if the search users is member of the group
         if($user.LoginName -eq $SearchUser)
          {
           #Write-Host  "$SearchUser is Member of " $WebRoleAssignment.Member.Name "Group"
            #Get the Group's Permissions on site
         $WebGroupPermissions=@()
            foreach ($RoleDefinition  in $WebRoleAssignment.RoleDefinitionBindings)
            {
                           $WebGroupPermissions += $RoleDefinition.Name +";"
                           }
         #write-host "Group has these permissions: " $WebGroupPermissions
         
         #Send the Data to Log file
         "$($Web.Url) `t Site `t $($Web.Title)`t Member of $($WebRoleAssignment.Member.Name) Group `t $($WebGroupPermissions)" | Out-File UserAccessReport.csv -Append
        }
       }
      }
                    }
    }
    
    #********  Check Lists with Unique Permissions ********/
              foreach($List in $Web.lists)
              {
                  if($List.HasUniqueRoleAssignments -eq $True -and ($List.Hidden -eq $false))
                  {
                     #Get all the users granted permissions to the list
                foreach($ListRoleAssignment in $List.RoleAssignments ) 
                    { 
                      #Is it a User Account?
         if($ListRoleAssignment.Member.userlogin)    
          {
             #Is the current user is the user we search for?
             if($ListRoleAssignment.Member.LoginName -eq $SearchUser)
            {
             #Write-Host  $SearchUser has direct permissions to List ($List.ParentWeb.Url)/($List.RootFolder.Url)
             #Get the Permissions assigned to user
              $ListUserPermissions=@()
                foreach ($RoleDefinition  in $ListRoleAssignment.RoleDefinitionBindings)
                {
                                $ListUserPermissions += $RoleDefinition.Name +";"
                               }
             #write-host "with these permissions: " $ListUserPermissions
             
             #Send the Data to Log file
             "$($List.ParentWeb.Url)/$($List.RootFolder.Url) `t List `t $($List.Title)`t Direct Permissions `t $($ListUserPermissions)" | Out-File UserAccessReport.csv -Append
            }
          }
          #Its a SharePoint Group, So search inside the group and check if the user is member of that group
         else  
          {
                             foreach($user in $ListRoleAssignment.member.users)
                                 {
              if($user.LoginName -eq $SearchUser)
               {
                #Write-Host  "$SearchUser is Member of " $ListRoleAssignment.Member.Name "Group"
                 #Get the Group's Permissions on site
              $ListGroupPermissions=@()
                 foreach ($RoleDefinition  in $ListRoleAssignment.RoleDefinitionBindings)
                 {
                                $ListGroupPermissions += $RoleDefinition.Name +";"
                                }
              #write-host "Group has these permissions: " $ListGroupPermissions
              
              #Send the Data to Log file
              "$($Web.Url) `t Site `t $($List.Title)`t Member of $($ListRoleAssignment.Member.Name) Group `t $($ListGroupPermissions)" | Out-File UserAccessReport.csv -Append
             }
            }
         } 
                       }
                }
              }
    } 
   }
     
  }

#Call the function to Check User Access
GetUserAccessReport "http://SharePoint.company.com" "Domain\User"

and the Output in Excel:
Audit & Permissions Report for a particular user Access in SharePoint

SharePoint Document Versions Size Report with PowerShell

$
0
0
This is a PowerShell version of my existing post Version History Size Report for SharePoint which uses C# object model to generate versioning report and gives insights, such as:
  • Site/Library's Total versions size
  • Total No. of versions created
  • Which documents are with more versions
  • Type of the documents
  • Library in which the document stored. Library Size with/Without versions
  • When was the last version modified
  • Size of the document's latest version
  • How much storage space being occupied by versions
  • Total size of the document including versions
PowerShell Script to generate Document Versions Report:
# Get Size of all Sub-sites in a Site Collection
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Region MOSS2007-CmdLets

Function Get-SPWebApplication()
{   
  Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
  return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
}

Function global:Get-SPSite()
{
  Param( [Parameter(Mandatory=$true)] [string]$SiteCollURL )

   if($SiteCollURL -ne '')
    {
    return new-Object Microsoft.SharePoint.SPSite($SiteCollURL)
   }
}
 
Function global:Get-SPWeb()
{
 Param( [Parameter(Mandatory=$true)] [string]$SiteURL )
  $site = Get-SPSite($SiteURL)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
            }
    return $web
}
#EndRegion

 Function GenerateVersionSizeReport()
 {  
    #Define 'Web Application URL' as Mandatory Parameter
    Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
 
 #Get the Web Application
    $WebApp=Get-SPWebApplication($WebAppURL)

    #Write the CSV Header - Tab Separated
 "Site Name`t Library `t File Name `t File URL `t File Type `t Last Modified `t No. of Versions `t Latest Version Size(MB) `t Versions Size(MB) `t Total File Size(MB)" | out-file VersionSizeReport.csv

 #Loop through each site collection
  foreach($Site in $WebApp.Sites)
   {
    #Loop through each site in the site collection
     foreach($Web in $Site.AllWebs)
   {
            #Loop through  each List
            foreach ($List in $Web.Lists)
            {
                #Get only Document Libraries & Exclude Hidden System libraries
                if ( ($List.BaseType -eq "DocumentLibrary") -and ($List.Hidden -eq $false) )
                {
                    foreach ($ListItem  in $List.Items)
                    {
          #Consider items with 1+ versions
                        if ($ListItem.Versions.Count -gt 1)
                        {
          $versionSize=0

                            #Get the versioning details
                            foreach ($FileVersion in $ListItem.File.Versions)
                            {
                                $versionSize = $versionSize + $FileVersion.Size;
                            }
       #To Calculate Total Size(MB)
       $ToalFileSize= [Math]::Round(((($ListItem.File.Length + $versionSize)/1024)/1024),2)
       
                            #Convert Size to MB
                            $VersionSize= [Math]::Round((($versionSize/1024)/1024),2)
       
       #Get the Size of the current version
       $CurrentVersionSize= [Math]::Round((($ListItem.File.Length/1024)/1024),2)
       
                            #Get Site Name
                            if ($Web.IsRootWeb -eq $true)
                            {
                                $siteName = $Web.Title +" - Root";
                            }
                            else
                            {
                                $siteName= $Site.RootWeb.Title + " - " + $Web.Title;
                            }

                            #Log the data to a CSV file where versioning size > 0MB!
                            if ($versionSize -gt 0)
                            {
                                "$($siteName) `t $($List.Title) `t $($ListItem.Name) `t $($Web.Url)/$($ListItem.Url) `t $($ListItem['File Type'].ToString()) `t $($ListItem['Modified'].ToString())`t $($ListItem.Versions.Count) `t $CurrentVersionSize `t $($versionSize) `t $($ToalFileSize)" | Out-File VersionSizeReport.csv -Append
                            }
                        }
                    }
                }
            }
  $Web.Dispose()          
        }
 $Site.Dispose()          
    }
    #Send message to console
    write-host "Versioning Report Generated Successfully!"
}

#Call the Function to Generate Version History Report
GenerateVersionSizeReport "http://sharepoint.crescent.com"

and the output after importing Data to Microsoft Excel:
 After adding Pivot chart for analysis:

You can download the script from MSDN: SharePoint Document Versions Size Report for SharePoint 2010 and MOSS 2007

Few Additions to the Script:
  1. Exclude SharePoint's System Lists & Libraries: You may want to exclude Lists and Libraries SharePoint uses for its own operations. E.g. "Pages". Just have a array with all system lists and exclude them from processing. 
  2. You may want to compare date. Such as: consider documents which are more than one year old (in other words, Last modified date > 1 year from now)
Here is the updated script, satisfying above requirements:
# Get Size of all Sub-sites in a Site Collection
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null

#Region MOSS2007-CmdLets

Function Get-SPWebApplication()
{   
  Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
  return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
}

Function global:Get-SPSite()
{
  Param( [Parameter(Mandatory=$true)] [string]$SiteCollURL )

   if($SiteCollURL -ne '')
    {
    return new-Object Microsoft.SharePoint.SPSite($SiteCollURL)
   }
}
 
Function global:Get-SPWeb()
{
 Param( [Parameter(Mandatory=$true)] [string]$SiteURL )
  $site = Get-SPSite($SiteURL)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
            }
    return $web
}
#EndRegion

 Function GenerateVersionSizeReport()
 {  
    #Define 'Web Application URL' as Mandatory Parameter
    Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
 
 #Get the Web Application
    $WebApp=Get-SPWebApplication($WebAppURL)

    #Write the CSV Header - Tab Separated
 "Site Collection Name `t Site Name`t Library `t File Name `t File URL `t File Type `t Last Modified `t No. of Versions `t Latest Version Size(MB) `t Versions Size(MB) `t Total File Size(MB)" | out-file VersionSizeReport.csv

 #Arry to Skip System Lists and Libraries
 $SystemLists =@("Pages", "Converted Forms", "Master Page Gallery", "Customized Reports", "Documents", 
                 "Form Templates", "Images", "List Template Gallery", "Theme Gallery", "Reporting Templates", 
         "Site Collection Documents", "Site Collection Images", "Site Pages", "Solution Gallery", 
                               "Style Library", "Web Part Gallery","Site Assets", "wfpub")
 
 #Get Last Year's Same day!
 $DateFilter=([DateTime]::Now.AddYears(-1))

   #Loop through each site collection
  foreach($Site in $WebApp.Sites)
   {
    #Loop through each site in the site collection
     foreach($Web in $Site.AllWebs)
   {
            #Loop through  each List
            foreach ($List in $Web.Lists)
            {
                #Get only Document Libraries & Exclude Hidden System libraries
                if ( ($List.BaseType -eq "DocumentLibrary") -and ($List.Hidden -eq $false) -and($SystemLists -notcontains $List.Title) )
                {
                    foreach ($ListItem  in $List.Items)
                    {
          #Consider items with 5+ versions And apply Date Filter
                        if ( ($ListItem.Versions.Count -gt 5) -and ( $ListItem['Modified'] -lt $DateFilter))
                        {
          $versionSize=0

                            #Get the versioning details
                            foreach ($FileVersion in $ListItem.File.Versions)
                            {
                                $versionSize = $versionSize + $FileVersion.Size;
                            }
       #To Calculate Total Size(MB)
       $ToalFileSize= [Math]::Round(((($ListItem.File.Length + $versionSize)/1024)/1024),2)
       
                            #Convert Size to MB
                            $VersionSize= [Math]::Round((($versionSize/1024)/1024),2)
       
       #Get the Size of the current version
       $CurrentVersionSize= [Math]::Round((($ListItem.File.Length/1024)/1024),2)

                            #Log the data to a CSV file where versioning size > 0MB!
                            if ($versionSize -gt 0)
                            {
                                "$($Site.RootWeb.Title) `t $($Web.Title) `t $($List.Title) `t $($ListItem.Name) `t $($Web.Url)/$($ListItem.Url) `t $($ListItem['File Type'].ToString()) `t $($ListItem['Modified'].ToString())`t $($ListItem.Versions.Count) `t $CurrentVersionSize `t $($versionSize) `t $($ToalFileSize)" | Out-File VersionSizeReport.csv -Append
                            }
                        }
                    }
                }
            }
  $Web.Dispose()          
        }
 $Site.Dispose()          
    }
    #Send message to console
    write-host "Versioning Report Generated Successfully!"
}

#Call the Function to Generate Version History Report
GenerateVersionSizeReport "http://sharepoint.crescent.com"

Dynamic Fusion Charts from SharePoint 2010 List Data

$
0
0
I said it before, and I'm saying it again: "Fusion Charts is a great product!" .In my earlier fusion chart implementations, most of the cases, charts are generated with predefined category. In some cases, I've fusion charts generated for SharePoint 2010 with dynamic categories as well.

Here is one among them: Had a List for tracking project risks and the requirement is to generate a Pie chart based on Risk count. Here is my "Risk Metrics" List structure. Among bunch of fields, I took only "Project Name" field and calculate its count for my requirement.
Fusion Chart SharePoint 2010

Steps to Create Dynamic Fusion Charts from SharePoint List
Simple! just download the Fusion Chart Free version and upload the SWF files to a SharePoint Document library. Create a Web Part Page, Insert a Empty Data View Web Part, Drag & Drop Relevant fields to the web part (in my case its "Project Name"), Change the XSL accordingly. Refer my existing posts on Fusion Chart for SharePoint - step by step procedures.

XSL for Generating Dynamic Fusion Charts from SharePoint List Data:
After Removing everything between
<xsl:template name="dvt_1.body"><xsl:param name="Rows"/>
and
</xsl:template>

<xsl:template name="dvt_1.body"><xsl:param name="Rows"/><xsl:variable name="varColorString" select="'XXXXXXAFD8F8F6BD0F8BBA00FF8E46008E8ED646468E468E588526B3AA00008ED69D080DA186BE'" /><xsl:variable name="varChartValue"><xsl:for-each select="$Rows[not(preceding-sibling::Row/@Project_x0020_Name = @Project_x0020_Name ) and @Project_x0020_Name!='']"><xsl:sort select="@Project_x0020_Name"/> <xsl:variable name="varTemp" select="@Project_x0020_Name"/>&lt;set name=&apos;<xsl:value-of select="translate(@Project_x0020_Name,'&amp;','-')"/>&apos; value=&apos;<xsl:value-of select=" count($Rows[@Project_x0020_Name = $varTemp])"/>&apos; color=&apos;<xsl:value-of select="substring($varColorString, position()*6+1,6)" />&apos; /&gt; </xsl:for-each><br/></xsl:variable><xsl:variable name="varChartData">&lt;graph caption=&apos;Open risks &apos; xAxisName=&apos;Project Name&apos; yAxisName=&apos;Count&apos; showNames=&apos;1&apos; decimalPrecision=&apos;0&apos; formatNumberScale=&apos;0&apos; pieYScale=&apos;45&apos; pieRadius=&apos;70&apos; animation=&apos;1&apos; shadowXShift=&apos;4&apos; shadowYShift=&apos;4&apos; shadowAlpha=&apos;40&apos; pieFillAlpha=&apos;95&apos; &gt;<xsl:value-of select="$varChartValue" />&lt;/graph&gt;   </xsl:variable><tr><td><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="500" height="400"><param name="movie" value="http://sharepoint.crescent.com/charts/FCF_Pie2D.swf?chartWidth=500&amp;chartHeight=400" ><xsl:text xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" ddwrt:whitespace-preserve="yes" xml:space="preserve"></xsl:text><param name="FlashVars" value="&amp;dataXML={$varChartData}&amp;chartWidth=500&amp;chartHeight=400"><param name="quality" value="high" /></param></param></object></td></tr> </xsl:template>

Chart Output:
Dynamic Fusion Charts from SharePoint 2010 List Data



Set Permissions and Restrict Access to SharePoint Views

$
0
0
Little background: PMO from Sales domain came with this requirement: They Have a list for capturing project metrics in a project collaboration SharePoint Site with the below columns:
sharepoint restrict access to views

There are two requirements:
  1. When Project Managers logs in, they should get projects in which they are assigned as "Project Managers".
  2. When Program Manager logs in, He should get all of the projects.
To solve the first requirement, I asked them to set the view filter as: "[Project Manager] is equals to [ME]", simple, uh?

For the second requirement, Program Manager should get all projects, nothing comes to my mind other than creating a separate view without filters. But how do we restrict normal users/ project managers from accessing the view for Program Managers? (of course, PMOs can create private views, but they don't wanted to!). So, Lets restrict access and secure view by setting permissions.

Set Permission on SharePoint View:

SharePoint doesn't any direct ways to Set Permissions and Restrict Access to SharePoint Views Out-of-the-box. Lets use this trick to get the permissions applied to SharePoint list views.
1. Create a List view page in the list, Say "PMO.aspx"
2. Move the View to any document library (E.g. to "Site Pages" library)
3. Break the Permissions of the page, Grant access to "Program Managers" group
4. Move the View page back to List.


Here is the detailed Step by Step:

Step 1: Create a List view page in the list
Open the site in SharePoint Designer, Navigate to the List (say: Project Metrics), Right click the List in Treeview >> Click on "New" >> List View Page
sharepoint restrict access list views

Give it a Name, Say: "PMO" and click "OK". This will create new aspx page: PMO.aspx.
sharepoint secure list view

Step 2: Move the View Page to "Site Pages" Library
Since lists doesn't provide a way to apply item level permissions on list view forms, we need to move the list page to a document library, Apply the permissions and then move the view page back to the list. So lets cut the PMO.aspx from Project Metrics List
sharepoint 2010 set permissions view

Paste the PMO.Aspx into "Site Pages" Libary
set permissions on a view sharepoint

Set permissions on SharePoint views: Now, Navigate to "Site Pages" library from browser. Click on "Manage Permissions"
restrict access sharepoint views

Click on "Stop Inhering permissions" from Ribbon to break the list view's permissions.
set permissions list views sharepoint 2010
Leave the users/groups who needs access to the view and remove all others. By this we have restricted access to views with required users and groups.
restrict access to sharepoint list views
Now, Go back to the SharePoint Designer, Cut the page from "Site Pages" Library and Paste it back to "Project Metrics" list.
set permissions sharepoint list view

That's all, We are done setting permissions for SharePoint view!

When users logged in to the site, they'll get to see the secured view.
set permissions sharepoint views

But if they try to access our secured view "PMO" which is restricted access, they'll get "Access Denied"
sharepoint 2010 secure view

SharePoint Top Navigation Link: Open in New Window

$
0
0
There was a requirement is to add a link in intranet portal's top navigation bar. Provided on clicking the link, it should open in new window, as the site link added was developed in a different platform & environment other than SharePoint.

If publishing feature is enabled, we can just go to: Site Actions >> Site Settings >> Navigation (Under Look and Feel), Add a New link with "Open link in new window" check-box selected. That's all, We are done with opening top navigation link in new window!
sharepoint navigation hyperlink open new window
However, In the provided site we don't have publishing feature enabled. So, in site settings page, we saw "Top link bar" link instead of "Navigation". Unfortunately, it doesn't provide us an option to open links in new window.
sharepoint top link new window
Here is the Trick to Open SharePoint top navigation link in New Window: JavaScript!
In URL field, just enter: javascript:void(window.open('http://your-link.aspx','_blank')) 
open url new window sharepoint 2010
Even javascript:void(window.open('http://your-link.aspx')) will work!

In my case, I had to enter:
javascript:void(window.open('https://peoplesoft.crescent.com/employee/profile.aspx','_blank')) 
Same trick can be used to open SharePoint quick launch links in new window.

Change "Add New Item" Link Text to something more descriptive

$
0
0
Requirement:
End user's requirement is to change "Add New Item" link text to "Add New Risk Metrics" , so that it will be more meaningful on Risk metrics list.
sharepoint change add new item text
SharePoint 2010 change add new item text
Solution: 
In Content Editor Web Part, Place JavaScript that manipulates Add New Item text. In Detail:

1. Go to the target page >> Site actions>> Edit Page

2. Insert a CEWP just below the list view web part.

3. Place the cursor in CEWP, Click on "Edit HTML Source" link from HTML Ribbon Item's drop down menu.
sharepoint 2010 change add new item text
4. In Content Editor web part enter the script:
<script type="text/javascript">
  document.getElementById("idHomePageNewItem").innerHTML="Add New Risk Metrics"</script> 
sharepoint customize add new item link
5. Save the page! see the result in action.
sharepoint change add new item link
Use IE Developer Toolbox or Firefox Firebug to get the ID of similar links in other lists and libraries. E.g. For document library it is: "idHomePageNewDocument"

Tail:
Remove add new item link SharePoint 2010:
Edit the page and change List view web part's Toolbar Type to "No Toolbar" . If you see add new item link missing sharepoint 2010, change the list view web part's toolbar type to something other than "No Toolbar".

Turnoff Theme Customization by Disabling Enhanced Themes in SharePoint 2010

$
0
0
Enhanced Theming enables users to customize SharePoint themes further by selecting different colors and fonts. Enhanced theme is actually a hidden feature (GUID: 068bc832-4951-11dc-8314-0800200c9a66), stapled with many of the site templates by the BaseSiteStapling feature. It doesn't come up with "Blank Site" template, BTW.

If you want to restrict users from customizing themes further, you can disable enhanced theming feature. Here is how:
Disable-SPFeature -identity enhancedtheming -url http://sharepoint.company.com

Before Disabling Enhanced Theme:
SharePoint 2010 enhanced theme
After Disabling Enhanced Theme:
Disable SharePoint 2010 enhanced theme

Move SharePoint Site from one subsite to another within a Site Collection

$
0
0
Had a requirement to move a SharePoint site from one subsite to another site of the same site collection. Source site URL was: http://sharepoint.crescent.com/teams/marketing/us/Policies/ and it should be moved to http://sharepoint.crescent.com/teams/marketing/Policies/ ultimately, the aim was to move the "Policies" SharePoint site from "us" site to its top level site "marketing".

So, we need to move the subsite "Policies" which is under an another subsite "US" to Top level site "Marketing". Yes, fairly simple! I can do export-Import (Stsadm -o Export or Export-SPWeb). But found another easier way today: Edit "ServerRelativeUrl" property of SPWeb!

PowerShell:
#Get the Source Site
$web=Get-SpWeb "http://sharepoint.crescent.com/teams/marketing/us/Policies/"
$web.AllowUnsafeUpdates=$true
#Set the Target URL
$web.ServerRelativeUrl="/teams/marketing/Policies/"
$web.AllowUnsafeUpdates=$false
$web.update

As SharePoint Manager Tool supports write back some of the properties, we can utilize this tool to update the "ServerRelativeUrl" property of SPWeb.
Move SharePoint Site from one subsite to another within a Site Collection

Just updated Server relative Url property, Save it back, Done!

Deploy/Publish Nintex Workflow to Multiple Lists with PowerShell and Nintex Web Service

$
0
0
Requirement: We have three Nintex workflows. These three workflows to be deployed to all document libraries of a sub-site.

Nintex workflows provides web services to deploy Nintex workflow to multiple lists and libraries, which is explained in one of the Nintex whitepaper: How to create a workflow that automatically deploys other workflows, which calls the web service to publish provided workflow to multiple site's lists.

Instead of creating another workflow to deploy a workflow, I decided to use PowerShell and Nintex Web Service to deploy workflows on multiple lists.
You can use the same method, if you want to update your existing workflow with new workflow content!
Here goes my PowerShell script:

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

#Region MOSS2007-CmdLets

Function global:Get-SPSite()
{
  Param( [Parameter(Mandatory=$true)] [string]$SiteCollURL )
 
   if($SiteCollURL -ne '')
    {
    return new-Object Microsoft.SharePoint.SPSite($SiteCollURL)
   }
}

Function global:Get-SPWeb()
{
 Param( [Parameter(Mandatory=$true)] [string]$SiteURL )
  $site = Get-SPSite($SiteURL)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
            }
    return $web
}
#EndRegion

#Target SharePoint site URL
$WebURL="http://sharepoint.crescent.com/finance/CustomerApproval/"
#Get the Target Site
$Web=Get-SPWeb $WebURL
#Get the Target Lists 

#Nintex Web Service URL
$WebSrvUrl=$WebURL+"_vti_bin/nintexworkflow/workflow.asmx"

$proxy=New-WebServiceProxy -Uri $WebSrvUrl -UseDefaultCredential
$proxy.URL=$WebSrvUrl
#Path of the NWF Workflow File
$WorkflowFile= "C:\Documents and Settings\Salaudeen\Desktop\CustApproval.nwf"

#Get the Workflow from file
$NWFcontent = get-content $WorkflowFile

foreach($List in $web.lists)
 {
  #Get only document libraries. Leave the hidden and "Pending Approval Task" Document Library
  if ( ($List.BaseType -eq "DocumentLibrary") -and ($List.Hidden -eq $false) -and ($List.Title -ne "Pending Approval Tasks") )
   {
     write-host "Workflow is being Published to: "$List
     $proxy.PublishFromNWFXml($NWFcontent, $List.Title ,$List.Title+" Approval", $true)
     write-host "Done!"
   }
 }
If your workflow fails for some reason (e.g. column not found in the target list), workflow will be placed under "Unpublished workflows" category

SharePoint 2010 Top Navigation Drop Down Menu, Quick Launch Flyout

$
0
0
By default, SharePoint enables top navigation Fly out Menus when Publishing Feature is enabled. Other Site templates like Team Sites doesn't come up with top navigation flyout menus. However we can enable top navigation flyout menus by adjusting few parameters in master page.

Open the Master page in SharePoint designer, set "StaticDisplayLevels",  "MaximumDynamicDisplayLevels" values accordingly either in design view or in code view. Save and publish the master page.
sharepoint 2010 navigation flyout menu

This is also applicable, when we use custom site map providers for Top navigation! Here is an example of SharePoint 2010 top navigation drop down menu.


sharepoint 2010 top navigation drop down menu
Flyout Quick Launch Menu
Same trick works on SharePoint quick launch navigation as well to bring flyout menus. Adjust the "StaticDisplayLevels" and "MaximumDynamicDisplayLevels" values based on the navigation depth accordingly. (say: 1)

And the output goes like this:
Before:
sharepoint 2010 quick launch flyout menu
After the change, SharePoint 2010 quick launch flyout menu appears as:sharepoint flyout quick launch

Navigation Link Missing in SharePoint Site Settings

$
0
0
Created a site collection for "Marketing" team today and they came with a complaint: "I couldn't see Navigation link under site settings! As 'Navigation' component  gives more options, we need it badly! How do we get it?".

Ok, I went to: Site Actions  >> Site Settings >> Look and Feel >> Nope! couldn't see Navigation link. Yes, Navigation link is missing!! instead I see "Quick Launch" and "Top Link Bar" links.
navigation link missing sharepoint 2010

Users must have the Full Control or Design permissions on the site to get Navigation link BTW.

Cause:
The navigation link missing SharePoint 2010 because the site template is based on "Team Site" template. Navigation Link will be available on sites based on Publishing Site/Collaboration site templates or Navigation link appears on site collections with publishing feature enabled. (If not you'd see "Quick Links.")

Solution:
Activate "SharePoint Server Publishing Infrastructure" feature! Go to:
  • Site Actions >> Site Settings
  • Under "Site collection administration" section click on "site collection features"
  • Activate the "Office SharePoint Server Publishing Infrastructure" feature
  • Now for each site you can activate feature "Office SharePoint Server Publishing"
  • Done! You should be able to see the option "Navigation" under look and feel.
navigation link missing sharepoint

You can do it only if you are a site collection administrator.

Alright, Don't want to activate publishing feature but want to access Navigation component? Sure, the simple workaround for this issue: Just append /_layouts/AreaNavigationSettings.aspx to the URL. E.g. http://sharepoint.crescent.com/teams/marketing/_layouts/AreaNavigationSettings.aspx
look feel navigation link missing sharepoint 2010
Don't want to activate publishing feature but need "Navigation" link under site settings? No issues. Here is the trick to get Navigation link in site settings: Navigation is actually a hidden feature which gets activated when you activate "Publishing Feature". So, we can just activate the "Navigation" feature directly. This will fix navigation link missing for SharePoint 2007.

stsadm -o activatefeature -name "navigation" -url "http://sharepoint.crescent.com/sites/sales" -force

For SharePoint 2010, you can enable the feature with PowerShell and get navigation link:
Enable-SPFeature -Identity "navigation" -url "http://sharepoint.crescent.com/teams/marketing/"

Export Import Quota Templates in SharePoint with PowerShell

$
0
0
In SharePoint database attach method migration, Quota templates must be created manually between farms. Its a pain when you have multiple quotas defined. These PowerShell scripts simplifies the process by exporting quotas to a XML file and import it again to another farm.

PowerShell Script to Export/Import Quotas between environments:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") 

function Export-QuotaTemplates([string]$FileName)
{
 #Get the SharePoint Web Application Service
 $ContentService =[Microsoft.SharePoint.Administration.SPWebService]::ContentService

 #Define Quota Templates XML -Container wrap
 $QuotaTemplateXML = '<QuotaTemplates>'
 #Get all Quota Templates
 foreach ($QuotaTemplate in $contentService.QuotaTemplates)
 {
    #Add Quota Templates to XML
    $QuotaTemplateXML += '<QuotaTemplate>'
    $QuotaTemplateXML += '<ID>'+ $QuotaTemplate.QuotaID +'</ID>'
    $QuotaTemplateXML += '<Name>'+ $QuotaTemplate.Name +'</Name>'
    $QuotaTemplateXML += '<StorageMaximumLevel>'+ [int](($QuotaTemplate.StorageMaximumLevel/ 1024)/1024) +'</StorageMaximumLevel>'
    $QuotaTemplateXML += '<StorageWarningLevel>'+ [int](($QuotaTemplate.StorageWarningLevel/ 1024)/1024) +'</StorageWarningLevel>'<# These two Properties applicable only for SharePoint 2010 and above!
    $QuotaTemplateXML += '<UserCodeMaximumLevel>'+ $QuotaTemplate.UserCodeMaximumLevel +'</UserCodeMaximumLevel>'
    $QuotaTemplateXML += '<UserCodeWarningLevel>'+ $QuotaTemplate.UserCodeWarningLevel +'</UserCodeWarningLevel>'
    #>
    $QuotaTemplateXML += '</QuotaTemplate>'
 }
 #Wrap Into the closing element
 $QuotaTemplateXML += '</QuotaTemplates>'
 $QuotaTemplateXML| Out-File $FileName
 Write-Host "Exported Quota Templates!"
}

 #Call Import Quota Templates Function
 Export-QuotaTemplates "QuotaTemplates.xml"

Once Exported, We can copy the exported xml file to target environment and run the Import script.

PowerShell Script to Import Quota Templates:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") 

function Import-QuotaTemplates([string]$FileName)
{
   #Get the XML File Contents
   [xml]$QuotaTemplateXML = Get-Content $FileName

   $ContentService =[Microsoft.SharePoint.Administration.SPWebService]::ContentService
   #Get existing Quotas collection
   $QuotaTemplateColl = $ContentService.QuotaTemplates

   #Iterate throught each Quota Template
 foreach($QuotaTemplate in $QuotaTemplateXML.QuotaTemplates.QuotaTemplate)
 {
   Write-Host "Processing:" $QuotaTemplate.Name
  #Check if Quota Template already exists!
  if ($QuotaTemplateColl[$QuotaTemplate.Name] -ne $null) 
  {
   Write-Host ">> Quota template: " $QuotaTemplate.Name " Already exists!"
  }
  else #Create the Quota Template
  {
    $NewQuotaTemplate = new-object Microsoft.SharePoint.Administration.SPQuotaTemplate
   $NewQuotaTemplate.Name = $QuotaTemplate.Name
   $NewQuotaTemplate.StorageMaximumLevel = $QuotaTemplate.StorageMaximumLevel
   $NewQuotaTemplate.StorageWarningLevel = $QuotaTemplate.StorageWarningLevel<# These two Properties applicable only for SharePoint 2010 and above!
      $NewQuotaTemplate.UserCodeMaximumLevel = $QuotaTemplate.UserCodeMaximumLevel 
      $NewQuotaTemplate.UserCodeWarningLevel =  $QuotaTemplate.UserCodeWarningLevel
      #>
   $QuotaTemplateColl.Add($NewQuotaTemplate)

   Write-Host "    >> Quota template ", $NewQuotaTemplate.Name ," is imported to the Quota Templates"
  }
 }
 }

 #Call Import Quota Templates Function
 Import-QuotaTemplates "QuotaTemplates.xml"

In some cases, I saw site collections set to "Individual Quota" even before database attachment I copied the quota templates (dunno the cause but!). So, we can apply quotas in bulk. Here is how:
Set-SPSite -Identity "http://sharePoint.company.com/sites/sales" -QuotaTemplate "Gold - 1 GB"

Here "Gold - 1 GB" is our existing quota defined! For MOSS 2007, The code goes like:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") 

function global:Get-SPSite($url)
 {
    return new-Object Microsoft.SharePoint.SPSite($url)
 }

$contentService =[Microsoft.SharePoint.Administration.SPWebService]::ContentService

$QuotaTemplate = $contentService.QuotaTemplates["Gold - 1 GB"]
$site = Get-SPSite "http://sharepoint.company.com/"
$site.quota=$QuotaTemplate 

Courtesy: http://sharepointpsscripts.codeplex.com/

Creating SharePoint Search Scope to Find Only Documents

$
0
0
Requirement: End-User wants to get only documents in search results!

Solution: In brief, create a new search scope of "ContentClass" Type "STS_ListItem_DocumentLibrary". This will filter search results with in all the documents under SharePoint document libraries.

At high level, to get filter search results by only documents, We are going to:
  1. Create a New Search Scope
  2. Add Rules to Search Scope
  3. Create New Page for Search Results
  4. Set Search Core Results Web Part Scope Property
  5. Add New Tab to Search Center, Link the Search Page crated
I assume SharePoint search service application is already in place, up and running. (if not, create it first!)

Step 1: Create a New Search Scope:

Go to Central Administration>> Manage service applications>> Search Service Application (or whatever SSA created in your environment) >> Manage>> Click on "Scopes" Link in Search Administration.
Click on New Scope to Create a New Scope.
Give a Name to the scope. Say: "Search All Documents". Click "OK" to create the scope.
sharepoint document search

Step 2: Add Rules to Search Scope

Add Rules to our created scope by clicking "Add rules" link next to newly created scope.sharepoint search only document libraries
  • Choose "Property Query" in Scope Rule Type. 
  • Select "contentclass" in Property Query, enter "STS_ListItem_DocumentLibrary" as property value. 
  • Choose "Include..." under behavior.
sharepoint 2010 documents search scope
On clicking "Ok" button, You will see SharePoint saying "Scope will be updated in 14 Minutes". Fortunately, no need to wait so. Go back to Search Administration >> Click on "Start Update Now" link next to Scope Needing Update
sharepoint search multiple document libraries
Once scope updated, you can verify the scope results by checking our newly created scope.
sharepoint search scope for document library
Alright, we have the scope ready. Lets move forward to make it available to user from search center.

Step 3:Create New Page for Search Results

Go to Search Center site, Create a New Page (Don't have Search Center created? Then create a New page in your team site of "Search Results" Page Layout type).
sharepoint search for all document library
Give it a Name. say: SearchAllDocuments.aspx

Step 4: Set Search Core Results Web Part Scope Property

Edit SearchAllDocuments.aspx page, Edit "Search Core Results" web part.
Expand the web part properties, under Location Properties >> Enter the scope as: Search All Documents (which is the name of the scope we have created in step: 1). Click "Ok" to save the changes. Publish/Check-in the page.

 Step 5:Add New Tab to Search Center, Link the Search Page crated

Go to the Search Center site >> Get the Ribbon from Site actions >> Click on "Edit" button from the ribbon

Click on "Add New Tab"
Give name to the tab, say: Search All Documents, Enter "SearchAllDocuments.aspx" (or whatever page we created in Step 3) for page field.
That's all! Search for a keyword to see our work in action!!
sharepoint search documents only

As SharePoint 2010 supports search refinements, we can refine the results further by clicking appropriate links (e.g. "Word" under result type search refinements web part).

Using the same method, We can filter search results based on other properties supported. For all available ContentClass parameters, refer http://msdn.microsoft.com/en-gb/library/dd584327%28office.11%29.aspx
E..g. You want to get all task list items. or you may want to search only surveys or picture libraries, etc.

Hide Links in Site Settings Page with HideCustomAction

$
0
0
Problem: People makes SharePoint branding inconsistent by creating and applying random themes and breaks corporate branding. So need to stop users from creating & uploading new themes and applying them.

Solution:
Hide Themes and Site Themes links with "HideCustomAction" from Site Settings!
Some time back, I created a feature to Hide "Delete this site" link from Site settings. Lets re-use the same trick to build a feature to hide "Themes" link from site settings page from everyone. Lets gets started.

1. Create New "Empty SharePoint Project" in Visual Studio 2010. Give it a name. Say: Crescent.TeamSite.HideThemes. Make it a Farm Solution.

2. Add a Feature to the project by right clicking "Features" node in the Solution Explorer, Add Feature

3. Add new Module to the Project, by Right clicking the project Crescent.TeamSite.HideThemes from solution explorer and choose "Add >> New Item", Give it a name. Say: HideThemes

Now the project structure should look like:

4. Update the Elements.xml file inside module we created:
<HideCustomAction 
  GroupId = "Customization"
  HideActionId = "Theme"
  Location = "Microsoft.SharePoint.SiteSettings"> </HideCustomAction><HideCustomAction
GroupId = "Galleries"
HideActionId = "Themes"
Location = "Microsoft.SharePoint.SiteSettings"></HideCustomAction>

Element.xml file should look like:

5. Go to the Feature Designer: Right Click "HideThemes" under Features node, choose "View Designer"

6. Provide name to the feature, as: "Hide Themes in Site Settings", set the scope as Site and include the Module we created "Hide Themes Module"

7. Build and deploy the Project


8. Activate the Feature: Go to Site actions >> Site Settings >> Site Collection Features >> Click on Activate next to "Hide Themes in Site Settings"


and the Result: See that the "Themes" link is hidden under Galleries!
 
Finally, We made the feature hidden, Activated for required site collections and we are done!

Refer MSDN to get Default Custom Action Locations and IDs

Additional Tip: Use IE Developer Toolbox or Firefox FireBug to Get the GroupID and HideActionID values.
get customactionid using IE Developer toolbar, Firebug

Disable Themes for All Sites in a Web Application
To stop users from applying themes at web application level, We can simply disable the web application user permissions "Apply Themes and Borders  -  Apply a theme or borders to the entire Web site." by going to: Central Administration >> Application Management >>Manage Web Applications >> Select the desired web app >> Click on "User Permissions" from Ribbon
web application user permissions

However, this will disable all users including farm administrator from applying themes and give error message "Attempted to perform an unauthorized operation." when they try to apply themes. There is a another way to disable themes by editing "SPTHEME.XML" file from 14 hive, which is not recommended!

But the actual requirement is to not to disable themes in all site collection of the web application. Now the question is: How to stop users from accessing "Themes" and "Site Themes" links on particular site collection(s)? So we made the feature, and activated wherever required.

Redirect Old MOSS 2007 Site to New SharePoint 2010 Site in Migration

$
0
0
In a database attachment method of migration from MOSS 2007 to SharePoint 2010, we gradually moved site collections one by one by attaching content databases of individual site collections. It took a while to address migration fixes and make them in a good shape for each site collection.

Meanwhile, had to redirect Users to migrated SharePoint 2010 site collections when they hit old MOSS 2007 site collection URLs or access them from bookmarks. Ideally, once migration is completed, we must place a server redirect in publishing server (like F5/ISA) or DNS change to send users from old URL to new URL.

But in our case, As we move site collections one by one, only few site collections needs to be redirected.

Solution: IIS URL Rewrite Module! Lets create a URL Rewrite Rule to redirect from old MOSS 2007 site collection to migrated SharePoint 2010 site. Say our:
  • Source: "http://moss2007.company.com/sites/marketing" 
  • Target: "http://sharepoint2010.company.com/sites/marketing".
Implementation:
Step 1: To start with, download and install URL Rewrite Module in Web Front End(WFE) Server(s) from: http://www.iis.net/download/urlrewrite
sharepoint 2010 URL rewrite redirect

Step 2: Once installed, Go to IIS Manager >> Select your Source SharePoint web site (moss2007.company.com) >> In Right pane, open "URL Rewrite" Module
redirect sharepoint site iis

Step 3: Create new inbound rule by clicking Add Rule(s) >> "Blank rule" >> Give it a Name, say: "Redirect Marketing Site collection".
sharepoint redirect to site collection

Step 4: Under Match URL section, specify values as:
  • Request URL: Matches the Pattern 
  • Using: Regular Expression 
  • Pattern: (.*)
  • Select Ignore case check box
sharepoint redirect site

Step 5: Under conditions section, specify values as:
Logical grouping:
Match All
Click on Add button and enter:

  •         Condition input: {URL}
  •         Check if input string: Matches the Pattern
  •         Pattern: /sites/marketing(/.*)
  •         Select "Ignore case" check box
sharepoint redirect entire site

Step 6: In "Action" section, Enter the values as:

  • Action Type: Redirect
  • Redirect URL: Enter the target URL E.g. Http://sharepoint2010.company.com/sites/marketing"
  • Select "Append Query String" check box
  • Redirect Type: Permanent(301)
sharepoint redirect a site

Step 7: Save the rule by clicking "Apply" link from Right action Pane!

That's all! Moving forward, when users hit "http://moss2007.company.com/sites/marketing" , they'll be redirected to "http://sharepoint2010.company.com/sites/marketing".
Viewing all 1058 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>