Sunday, July 27, 2014

Add Attachment Field in SharePoint 2013 List Form

Requirement: Add attachment column to a custom new/edit forms in SharePoint 2013.

Solution:
Create new custom list forms for New and Edit in SharePoint designer 2013, Add this code to the custom list form in the location where you want the attachment field to appear.
  
<td colspan="2">
 <table>
 <tr>
  <td style="width:170px">
       <b>Upload Approval E-Mails:    </b>
  </td>
  <td valign="top" class="ms-formbody" id="attachmentsOnClient">
   <input type="file" name="fileupload0"  id="onetidIOFile" size="50" title="Name">   </input>
  </td>
  <td>
   <input name="attachButton" type="button" value="Attach" onclick='OkAttach()'  />
  </td>  
 </tr>
      </table>
</td>    
Result: Here is the SharePoint custom edit form with attachment field.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, July 23, 2014

Export-Import All Lists and Libraries from One Site to Another using PowerShell

Requirement is to copy and paste all SharePoint lists and libraries from one site to another. While "Save List as a Template" is one approach, it doesn't work for larger lists and its time consuming. Using Central Administration export method also kills my time.
export import sharepoint list using powershell

Solution: We can copy and paste SharePoint lists using PowerShell script.

Export document library using PowerShell in SharePoint 2013:
Syntax:
Export-SPWeb <<Web-URL>> –Path <<Backup-Path>> -ItemURL <<Library-URL>> –IncludeUserSecurity  -IncludeVersions All

E.g.
Export-SPWeb http://sharepoint.crescent.com/Teams/2015-ESG/ –Path "D:\Documents.cmp" -ItemURL "Documents" –IncludeUserSecurity  -IncludeVersions All
 

Import document library in SharePoint 2013 using PowerShell:

Syntax:
Import-SPWeb <<web-URL>> -path <<Backup-file>> –force –IncludeUserSecurity -UpdateVersions Overwrite

E.g.
Import-SPWeb https://sharepoint.crescent.com/Teams/2016-ESG/" -Path "D:\Documents.cmp" –force –IncludeUserSecurity -UpdateVersions Overwrite
 

Export-Import all lists and libraries from one site to another site using PowerShell:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#Custom PowerShell Function to Export All Lists and Libraries from a SharePoint site
Function Export-AllLists($WebURL, $ExportPath)
{
   #Get the source web
   $web = Get-SPWeb $WebURL

   #Check the Local Folder export Lists
    
   #Get all lists - Exclude System lists
   $ListCollection = $web.lists | Where-Object  { ($_.hidden -eq $false) -and ($_.IsSiteAssetsLibrary -eq $false) -and ($_.Author.LoginName -ne "SHAREPOINT\system") }

   #Iterate through each list and export
   foreach($list in $ListCollection)
    {
        Write-host "Exporting: " $list.Title
        #Remove : from List title - As we can't name a file with : symbol
        $ListTitle = $list.Title.Replace(":","")
        Export-SPWeb $WebURL -ItemUrl "/$($list.RootFolder.Url)" -IncludeUserSecurity -IncludeVersions All -path ($ExportPath + $ListTitle+ ".cmp") -nologfile
    } 
}

#Custom PowerShell Function to Export All Lists and Libraries from a SharePoint site
Function Import-AllLists($WebURL, $ImportPath)
{
   #Get the Target web
   $web = Get-SPWeb $WebURL

   #Check the Local Folder export Lists
    
   #Get all File Backups to Import
   $FilesCollection = Get-ChildItem $ImportPath

   #Iterate through each file and import
   foreach($File in $FilesCollection)
    {
        Write-host "Importing: " $File.Name
        Import-SPWeb $webURL -path $ImportPath$File -includeusersecurity -UpdateVersions Overwrite -nologfile
    } 
}

#Call the function to export
Export-AllLists "http://sales.crescent.com/" "D:\Backup\"
#To import, Use:
#Import-AllLists "http://marketing.crescent.com/" "D:\Backup\"
This script helped me to move all lists from a highly customized and corrupted site to a clean SharePoint site.Here is my another PowerShell script to copy-paste all lists and libraries between Sites: Copy SharePoint List or Library between Sites with PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, July 22, 2014

Save Site as Template Option Missing in SharePoint 2013?

Perhaps the most easiest way to create a standard site template is to Create a site,  Add-remove content, list and libraries and save it as a template. But SharePoint 2013 does not support "Save Site as Template" option on Publishing sites. If a site with "SharePoint Server Publishing" is activated this option will not available in  Site settings, So you can't save site as template!

In SharePoint 2007 and  SharePoint 2010 we use a trick by appending the URL: "/_layouts/savetmpl.aspx" to get this functionality! Unfortunately, you cannot save site as template in SharePoint 2013 using this trick! if you try accessing the page with the above trick, you'll get an error message:

Sorry, Something went wrong - The "Save site as template" action is not supported on this site.
save site as template sharepoint 2013 error Sorry, Something went wrong - The "Save site as template" action is not supported on this site.

Enable save site as template in SharePoint 2013 publishing sites:
How to enable save site as template SharePoint 2013? Well, this issue can be resolved by either of these two ways:
  1. Setting "SaveSiteAsTemplateEnabled" property of the site to true
  2. Using PowerShell to Enable Save site as template feature.

Option 1: Save site as template option with SharePoint designer 2013:
  • Open your site with SharePoint Designer 2013
  • Click on ‘site options’ button from the ribbon.   
  • Under parameters tab, locate the option for “SaveSiteAsTemplateEnabled” and change this setting to "True"
    how to enable save site as template in sharepoint 2013
  • Click on OK button to save your changes.

Option 2: Enable Save site as template SharePoint 2013 with PowerShell:
Run this PowerShell script to enable save site as template in SharePoint 2013.
Add-PSSnapin Microsoft.SharePoint.PowerShell

$SiteURL ="http://intranet.crescent.com/sites/operations"

$web = Get-SPWeb -Identity $SiteURL

#Enable Save Site as template option
$web.SaveSiteAsTemplateEnabled = $true
$web.Update()
 
So now, When you access the save site as template URL shortcut: _layouts/savetmpl.aspx (Such as:
http://your-site-url/_layouts/savetmpl.aspx) You should be able to get the save site as template page.
 save site as template sharepoint 2013 publishing site



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Property Bags in SharePoint 2013 - Store, Retrieve Custom Configurations

As its name suggests, Property bag feature provides a convenient way to store and retrieve custom configurations, instead of having to store them in web.config files. Property bags in SharePoint stores configuration data in the Hash-Table (Key-Value) format. We can store and retrieve properties at the following levels: 
  1. Farm (SPFarm )
  2. Web application (SPWebApplication )
  3. Site collection (SPSite )
  4. Site (SPWeb )
  5. List (SPList )
  6. Folder (SPFolder)
  7. File (SPFile)
  8. List Item (SPListItem)
Property bags can be created, edited and deleted at all of these level.  Property bag keys are case sensitive!

How to use property bag SharePoint?
If your SharePoint application uses any specific setting for each and individual SharePoint object, such as Web Application, Site Collection, Site, etc. you have maintain those entries in the config files. Here is where SharePoint property bags can be a great helper.

There is no out-of-box user interface to manage property bag settings in SharePoint. We use object model codes to set/get properties programmatically. Any method that interacts with SharePoint object properties such as AddProperty, DeleteProperty, GetProperty, SetProperty doesn't has any effect on "Properties" property. You have to access "AllProperties" instead.  "Property" property is available for backward compatibility.

Managing SharePoint Property bag using PowerShell:
Here is an example to manage Property bag at the site level using PowerShell. 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebURL ="http://intranet.crescent.com/sites/Sales/APAC"
#Get the Web Object
$Web = Get-SPWeb -Identity $WebURL

#Variables for Key-Value 
$PropertyName ="masterPage"
$PropertyValue ="Crescentv1.Master"

#add property bag in sharepoint 2010/2013
$web.AddProperty($PropertyName,$PropertyValue) #add property bag
$web.Update()
Write-host "Created new Property: "$PropertyName

#how to read property bag in sharepoint - query property bag
Write-host "Retrieved $PropertyName Value:" $web.GetProperty($PropertyName)   

#set property bag sharepoint 2010 powershell
$PropertyNewValue ="Crescentv2.Master"
$web.SetProperty($PropertyName, $PropertyNewValue)
$web.Update()
Write-host $PropertyName updated with new value:$PropertyNewValue

#Search for a Property
if($web.AllProperties.ContainsKey($PropertyName))
 {
     #access property bag in sharepoint
     write-host Property Found! Value: $web.GetProperty($PropertyName)
 }
 
#Remove Property from Property Bag
$web.DeleteProperty($PropertyName)
$web.Update()
write-host "Property $PropertyName has been deleted!"

#Get all Properties from sharepoint property bag 
#$web.Allproperties

$Web.Dispose()

Same code can be translated in to C# object model to use with Event Receiver, Web Part, etc - Add new property bag at site collection level: Here is a SharePoint property bag example:
#Get Site collection
SPSite site = new SPSite("http://your-sharepoint-site-url");

//Add new Property bag key and value
//Old Method
//site.Properties.Add("MasterPage", "Crescentv1");
//site.Properties.Update()

//create property bag in sharepoint
site.AllProperties["MasterPage"] = "Crescentv1.master";
site.Update()
Tips: You can also manage property bag settings using SharePoint Designer!

SharePoint property bag codeplex Tools:
There are some codeplex utilities to manage SharePoint property bag settings.
  1. http://pbs2013.codeplex.com/
  2. http://sp2010dynsettings.codeplex.com/
  3. http://spm.codeplex.com/ - Can be used as a Property bag editor,viewer as well

SharePoint property bag access denied!
If you don't have permission to SharePoint objects you can't interact with them. E.g. To access/add SharePoint Farm property bag you must be a  SharePoint farm administrator. You may get "Access Denied" Error if not! Use Elevated Privileges to store and retrieve from such objects.

SharePoint property bag limitations: As its a HashTable - you can store data values up to 4 KB in size limit.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, July 21, 2014

Restart IIS (IISRESET) on All Servers in the SharePoint Farm using PowerShell

Doing IISReset on Server Farm with Multiple SharePoint servers is a painful processes. If you ever need to restart IIS on all servers in the SharePoint farm, Here is a nifty solution to do IISRESET on all SharePoint Servers using PowerShell:

PowerShell Script to Restart IIS on All SharePoint Servers:
   
 Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

 #Get All SharePoint Servers - Except DB and SMTP Servers
 $Servers = Get-SPServer | Where {$_.Role -ne "Invalid" }

    #Iterate through the list and restart one by one.
    foreach ($server in $servers)  
    {  
       Write-Host "Restarting IIS on server: $($Server.Name)"
       IISRESET $Server.Address
    
       #Optional: Get the Status
       Write-Host "IIS status for server $($server):"  
       IISRESET $server.Address /status
    } 
 Write-host "IIS Restarted on All Servers of the Farm!" -f Green

Make sure, you have "Local Administrator" Permission on all servers you want to reset IIS.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Set Max Degree of Parallelism for SharePoint 2013 in SQL Server 2012

SQL Server configuration option 'max degree of parallelism' limits the number of processors used for the execution of a query with a parallel plan. By default its set to '0' to allow all processors available.  SharePoint 2013 requires that "max degree of parallelism" option be set to exactly 1 to ensure each request is served by a single SQL Server process.

You may get configuration failed error in SharePoint 2013, if max degree of parallelism isn't set to 1.
This SQL Server instance does not have the required "max degree of parallelism" setting of 1. Database provisioning operations will continue to fail if "max degree of parallelism" is not set 1 or the current account does not have permissions to change the setting.
sharepoint 2013 configuration failed max degree of parallelism
In SharePoint 2010 days, Maximum Degree of Parallelism option was recommended, but optional. But in SharePoint 2013, it is mandatory to set its value to 1 otherwise SharePoint configuration wizard will fail.

Set Max Degree of Parallelism for SharePoint 2013 in SQL Server 2012
  1. Go to SQL Management Studio and connect to the instance which hosts SharePoint databases.
    sharepoint 2013 database max degree of parallelism
  2. From the Object Explorer pane, Right click on the SQL Server and select Properties.
    max degree of parallelism sql 2012 for sharepoint 2013
  3. From the Properties window, Select the 'Advanced' Node
  4. Scroll to the bottom and change the Max Degree of Parallelism value from 0 to 1. max degree of parallelism setting of 1 sharepoint 2013
  5. Click 'OK' to apply max degree of parallelism setting in SQL Server 2012.
If you are running the SharePoint configuration wizard with a user account that has sysadmin rights on SQL Server, max degree of parallelism will be automatically configured!

Enable "Max degree of parallelism" from SQL Server Management Studio - Transact-SQL:
You can set max degree of parallelism option from Transaction SQL by running below code from SQL Server Management Studio.
sp_configure 'show advanced options', 1;
GO
RECONFIGURE WITH OVERRIDE;
GO
sp_configure 'max degree of parallelism', 1;
GO
RECONFIGURE WITH OVERRIDE;
GO


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, July 20, 2014

SharePoint Site Collection vs Subsite - Determine Which One to Create

SharePoint newbies often get confused with this question: When to create Site collection and when to use Subsites? What are the advantages of having a Ste collection rather subsite? Well, the choice of Site collection or subsite can be determined based on these factors:
site collection or subsite best practice
  • Security/Permission Management - Every Site collection uses unique security model, which means: security is isolated between site collections. Whereas subsites can inherit security from its parent site. In an another aspect - permission management between site collections could be a nightmare. But managing permissions in subsites can be much easier and less frustrating.
  • Re-usability: Several SharePoint components such as web parts, content types, site columns (only in SharePoint 2007), etc can be reused within all sites in a site collection. But if you have to port them to other site collections, you may require considerable efforts.
  • Hierarchy/Navigation: Subsites can share a common navigation and structure. But site collections uses unique navigation (OOTB! Although custom site map providers can be implemented, it involves considerable efforts)
  • Governance/Scalability- Storage Quotas: Site collection's growth can be governed and controlled with storage Quotas. Whereas subsites doesn't has any such feature.We can't control storage growth of a subsite without splitting them into site collections that involves several known issues and URLs to be changed after converting subsites into site collection. But we can increase site collection's storage quota without affecting its URL structure. Site collections are easy to lock!
  • Content Database Scalability: Site collections are mapped with content databases as One - Many relationship. So one site collection can be placed only in a single DB. But One DB can hold multiple site collections), So that site collections can be easily moved between content databases or to different web applications.
  • Backup/Restore : Site collections completely supports backup-restore. Although subsites support  export-import, certain artifacts such as security, recycle bin, workflows, alerts, etc will be lost during export-import process. So, site collections are easy to replicate between different SharePoint environments.
  • Feature Scopes: Certain features are scoped at site collection level in SharePoint. E.g. Search scopes, Site collection Policies, Auditing, IRM, Recycle Bin, Usage reports, Site collection Administrators, site/list templates, Content and structure feature to copy/paste files within a site collection, etc.
  • Branding: Branding features such as Master pages, Themes, Display Template, CSS/JS files can be inherited by sub-sites to provide consistent look and feel seamlessly. But between site collections we'll have to deploy these individually.
  • URL Hierarchy: Site collections can have different URLs (Host-named site collections) or Unique URL underneath the managed path (such as: /sites/siteA or /teams/marketing), But subsites share the common Top Level URL and lay beneath it.
  • Web Part Boundaries: If you want to aggregate data throughout your site hierarchy using Web Parts like the Content Query Web Part, Data View Web Part and other data aggregation Web Parts, they work only within the site collection scope. They can't fetch data from other site collections. (up to SharePoint 2010! We've Content search web part in SharePoint Enterprise Edition!)
  • Site Templates - If you create your own site template by combining content, you'll end up creating only subsites from the template. 
  • Functional Classification: Create a site collection to host sites that are going to share something in common. E.g  Site collection for the business unit. Each business unit may contain multiple subsites. E.g. http://sharepoint.com/Sites/Sales/us/, /Sales/NA, etc. 
  • Software Boundaries: A site collection supports up to 250,000 subsites. Number Site Collections per Content Database - Recommendation 10000 - as of SharePoint 2013.
     


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, July 18, 2014

Database is in compatibility range and upgrade is recommended - Solution

Problem: 
After a service pack upgrade in SharePoint 2013, database status under  Central Admin >> Upgrade & Migration >> Review database status - turned into "Database is in compatibility range and upgrade is recommended"

Solution:
In most cases, this message simply means, You have installed a latest patch/service pack and running SharePoint products configuration wizard is pending still! So, run SharePoint products configuration wizard once to clear this message.
fix database is in compatibility range and upgrade is recommended

Still getting "Database is in compatibility range and upgrade is recommended" message?
To resolve this error with BDC service application, just execute below cmdlet in PowerShell console.
(Get-SPDatabase | ?{$_.type -eq "Microsoft.SharePoint.BusinessData.SharedService.BdcServiceDatabase"}).Provision()
Once its executed BDC database status turned to "No Action Required".

"Database is in compatibility range and upgrade is recommended" on Content databases
In SharePoint 2016 Central Administration, under database upgrade status page, found the status of a SharePoint content database as "Database is Running in Compatibility Range and Upgrade Recommended".
Database is Running in Compatibility Range and Upgrade Recommended
 Here is how to resolve it:
  • Run the cmdlet "Upgrade-SPContentDatabase" on the contend database once, which should resolve the problem.
    Get-SPContentDatabase –Identity <database-name> | Upgrade-SPContentDatabase
  • Run PSConfig command line: PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


"The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered" PowerShell Error Solution in SharePoint 2013/2010

We have a new SharePoint administrator joined in our team. We granted him access to all SharePoint servers, Added him to Farm Admin group, Web application policy. 

However, when he tried launching SharePoint Management Shell or try adding the SharePoint PowerShell snap-in from PowerShell ISE, got the error message:

 "The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered"

Solution: Grant Permissions to Run PowerShell Script on SharePoint 2013/2010
Basically, We've to grant "Shell Admin" access rights to be able to run PowerShell scripts in SharePoint. As the first step, Add the new user to "Local Administrator" group of the SharePoint WFE/App Servers. Login as with Farm Admin access rights and run:
 
Add-SPShellAdmin Domain\User
This cmdlet grants "SharePoint Shell Access" membership rights on the SharePoint Farm configuration database and adds the user under WSS_ADMIN_WPG group in all of SharePoint front end servers.

While the above cmdlet gives access to SharePoint Management shell, You have to grant access to all SharePoint databases as well:

Get-SPDatabase | Add-SPShellAdmin Domain\User

Important:
The Account in which you are running the above PowerShell cmd-lets should have "DB Creator" and "Security Admin" server roles in SQL Server and Local Administrator of the server from which you're running the cmdlet. By default, The Farm Admin account is granted with these rights during initial farm setup.

To get the list of all the users having the "SharePoint_Shell_Access" role, use the Get-SPShellAdmin. To delete a user from the "SharePoint_Shell_Access" role, use the Remove-SPShellAdmin .

Last but not least: You may also receive this error when UAC is turned ON. Use "Run as Administrator" on SharePoint Management Shell to overcome "The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered" error! 

Another case: Have you installed new version of PowerShell?
In an another scenario, We got this issue when the .Net framework and Windows Management framework update is installed. To resolve the issue, Just add "-version 2" to the "SharePoint 2010 Management Shell" link's target field.

FROM:
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe  -NoExit  " & ' C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\\sharepoint.ps1 ' "
TO:
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -Version 2.0 -NoExit " & ' C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\sharepoint.ps1 ' "

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, July 16, 2014

PowerShell "Exception of type 'System.OutOfMemoryException'"

In middle of a script execution, Got the below error:
The following exception was thrown when trying to enumerate the collection: "Exception of type 'System.OutOfMemoryException' was thrown.".
At d:\Scripts\VersionRpt.ps1:19 char:16
+         foreach <<<<  ($FileVersion in $File.Versions)
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
    + FullyQualifiedErrorId : ExceptionInGetEnumerator
PowerShell Exception of type 'System.OutOfMemoryException'

Solution:
Increase the PowerShell console memory! Here is how:
C:\

CD wsman:

#Get the current setting
Get-Item localhost\shell\maxmemoryperShellMB

#Increase the memory
Set-Item localhost\shell\MaxmemoryPerShellMB 2048
PowerShell "Exception of type 'System.OutOfMemoryException'"
BTW, You can also try disposing unused objects in PowerShell. Here, we got this exception due to the large number number of version.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Find All Site Templates Used by SharePoint Sites

Requirement: Find all Site templates used in a SharePoint 2010 environment and generate report prior proceeding with Migration, as certain templates are discontinued in SharePoint 2013.

Solution: Lets get site template usage report on all sites using PowerShell.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables
$WebAppURL="http://sp10.crescent.com" 

#Get All Webs
$WebsCollection = Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All | Get-SPWeb -Limit All

#Retrieve Site template data from each web
foreach ($web in $WebsCollection)
   {  
     $SiteName = $web.Title
     $SiteURL = $web.Url  
     $SiteTemplate = $web.WebTemplate  
     $TemplateID = $web.WebTemplateID  
     Write-Host " $($SiteName), $($SiteURL), $($SiteTemplate) ,$($TemplateID)"  
   } 

PowerShell Script to Get Web Templates of all sites and Export to CSV Report:
Lets tweak it a bit to find all site templates and export to Csv file.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Variables
$WebAppURL="https://portal.crescent.com"
$ReportFile="C:\Reports\WebTemplates.csv"
 
#Get All Webs
$WebsCollection = Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All | Get-SPWeb -Limit All

#Array to Hold Result - PSObjects
$ResultCollection = @()
 
#Retrieve Site template data from each web
foreach ($web in $WebsCollection)
   {  
        $Result = New-Object PSObject
        $Result | Add-Member NoteProperty SiteName($web.Title)
        $Result | Add-Member NoteProperty SiteURL($web.URL)
        $Result | Add-Member NoteProperty SiteTemplate($web.WebTemplate)
        $Result | Add-Member NoteProperty WebTemplateID($web.WebTemplateID)
        
        #Add the object with property to an Array
        $ResultCollection += $Result
   }

Write-host "Web Templates Report Generated Successfully!" -f Green

#Export the result Array to CSV file
$ResultCollection | Export-CSV $ReportFile -NoTypeInformation       
To find a site template being used by a particular site, Refer: How to find site template in SharePoint

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, July 15, 2014

How to Integrate Twitter with SharePoint to Get Twitter Feeds

Although there are Twitter-SharePoint web parts in codeplex, we can integrate twitter with SharePoint with Out-of-the-box script editor/content editor web parts in few steps.

Simply, follow these steps for adding twitter to SharePoint to get twitter feeds.

Step 1: Go to https://www.twitter.com and Log-in to your Twitter account.(You need to have a twitter account!)

Step 2: Navigate to Settings >> Widgets (https://twitter.com/settings/widgets)
twitter feed web part sharepoint 2010

Step 3: In the widgets tab, Click on "Create New" button
twitter feed in sharepoint 2013

Step 4:  Under "User Timeline" tab, Click on “Create Widget” button to generate Twitter embed code. You can further customize look and feel by following developer API references.
twitter sharepoint 2010 web part

Step 5: Wait for the “Your Widget has been created.” Message from twitter. Now Copy the twitter embed code to clipboard

twitter and sharepoint integration
Here is my twitter widget script generated:
<a class="twitter-timeline"  href="https://twitter.com/SharePointDiary"  data-widget-id="489002092749549570">Tweets by @SharePointDiary</a>
    <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

Step 6: Navigate to your SharePoint site. Add a content Editor web part wherever required (Edit Page >> Add Web Part). Paste the code copied from twitter into Content Editor’s Insert >>Embedded Code, Save and close! This will display twitter feeds in SharePoint sites.

Here is the end Result of Twitter SharePoint integration:
twitter integration sharepoint 2013


The above method works on SharePoint 2007, SharePoint 2010 and even in SharePoint 2013! compared with methods to show twitter RSS feed using XML Web parts, XSL in SharePoint, I consider the above method is relatively simple!
adding twitter to sharepoint 2007


Update: In SharePoint 2013, when "Minimal download strategy" feature is enabled, I see the twitter feeds are not rendering, instead it displays "Tweets by User"!

Solution: Either disable MDS feature or place the twitter code in a html file, save it in a library, display it in the page with Page viewer web part or with the help of "<iframe>" in CEWP!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, July 14, 2014

Add-SPShellAdmin: You need to have Machine administrator priviliges to run this cmdlet

While trying to add a new user to grant PowerShell script execution policies, Got this error message:

Add-SPShellAdmin: You need to have Machine administrator priviliges to run this cmdlet

Fix:
Although you are in  local server Administrator group, You must run the SharePoint Management Shell as Administrator. Simply right click on SharePoint 2010/2013 Management Shell  >> Choose "Run as a administrator"

Alternatively, you can disable the UAC to avoid these kind of issues.

Related article: How to disable UAC in Windows 2012



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, July 10, 2014

Download All Versions of a Document in SharePoint using PowerShell - Web Services

Requirement:
Wanted to extract and download each version of the document stored in a SharePoint library. Well, PowerShell can do it from client side using web services. Here is the PowerShell script to download each version to the local folder programmatically.

Download all versions of a document using PowerShell
# ******* Variables Section ******************
#Define these variables 
$WebURL="http://sharepoint.crescent.com/sites/Operations/"
$FilePath ="http://sharepoint.crescent.com/sites/Operations/docs/designDoc.docx"
$TargetFolder = "C:\Downloads"
# *********************************************

#Web Service URL
$WebServiceURL =$WebURL+"_vti_bin/Versions.asmx"
$WebService = New-WebServiceProxy -Uri $WebServiceURL -UseDefaultCredential
$WebService.URL=$WebServiceURL

#Get File name from file path
$FileName = $FilePath.Substring($FilePath.LastIndexOf("/")+1,($FilePath.Length-$FilePath.LastIndexOf("/")-1))

#Create the Target Library if it doesn't exists
    if (!(Test-Path -path $TargetFolder))
       {   
             #If it doesn't exists, Create
             $TargetFolder = New-Item $TargetFolder -type directory
       }


#Call web service method "GetVersions" to retrieve versions collection
$FileVersions = $WebService.GetVersions($FilePath).Result
 foreach($File in $FileVersions)
 { 
  #Frame the File name : E.g. 1.0_Filename.ext
  $VersionFileName = "$($TargetFolder)\$($File.version)_$($FileName)"
  write-host $VersionFileName
  $webclient = New-Object System.Net.WebClient
     $webclient.UseDefaultCredentials = $true
  write-host $File.url
     $webclient.DownloadFile($File.url,$VersionFileName)
  Write-Host "Downloaded version: $($File.Version)"
 }
Here is how the output looks like:
PowerShell to Download All Versions of a Document in SharePoint


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Expand-Collapse All Groups in SharePoint 2013 List Views using jQuery

SharePoint doesn't has the ability to expand/collapse all groups in grouped list views. However, with jQuery we can bring Expand All-Collapse All buttons in SharePoint 2013 grouped list views. Just edit the grouped view page (Site Actions Gear >> Edit Page), add a "Script Editor" Web part and then place the below code in it.

jQuery for Expand-Collapse all items in grouped views in SharePoint 2013:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.2.6.min.js"></script>

<script type="text/javascript">
  
    function expandAll() {
        $("img.ms-commentexpand-icon").click();
    }

    function collapseAll() {
        $("img.ms-commentcollapse-icon").click();
    }

    var expandButton = "<a href='#' onClick="

    +'"' + "this.href='javascript:expandAll()'"

    + '">&nbsp;<img title="expand all groups" style="border:none;" alt="expand all" src="/_layouts/images/collapseplus.gif"></a>';

    var collapseButton = "<a href='#' onClick="

    +'"' + "this.href='javascript:collapseAll()'"

    + '">&nbsp;<img title="expand all groups" style="border:none;" alt="collapse all" src="/_layouts/images/collapseminus.gif"></a>';

    $(document).ready(function () {
        $(".ms-pivotControl-container").append(expandButton).append(collapseButton);
    });
</script>
and here is the result:
Thanks to: https://www.nothingbutsharepoint.com/sites/eusp/pages/jquery-for-everyone-expandcollapse-all-groups.aspx for the idea!

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, July 9, 2014

MaximumFileSizePerExtension in SharePoint 2013

In SharePoint 2013, Maximum file upload size is increased to 250MB - which means users can upload any single file up to 250MB of size. If users try to upload a file which is larger than the configured web application limit, they receive an error message saying its exceeded the maximum length allowed!

SharePoint 2013 introduced a new feature called "MaximumFileSizePerExtension" to set maximum upload size exclusively for certain file types. Say for e.g. Your web application's default Maximum size for uploading files would be 250MB, But you can add an exception for "WMV" files up to 2GB!

By default, Microsoft One Note files (.ONE) are configured with 1GB size limit. Here are the PowerShell cmdlets to manage this configuration. To view file types set in MaximumFileSizePerExtension property:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebApp = Get-SPWebApplication "http://your-sharepoint-web-app-url"

$WebApp.MaximumFileSizePerExtension

This gives currently configured file extensions for maximum file size exclusions. To add a file type extensions, such as WMV, use the following PowerShell cmdlet:
$WebApp = Get-SPWebApplication "http://your-sharepoint-web-app-url"

$WebApp.MaximumFileSizePerExtension.Add("wmv",1024)

$WebApp.Update()

To remove file extension from Maximum file size:
$WebApp = Get-SPWebApplication "http://your-sharepoint-web-app-url"

$WebApp.MaximumFileSizePerExtension.remove("wmv")

$WebApp.Update()


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Get SharePoint Site Collection Created Date using PowerShell

Requirement: I had to generate a report for management review on list of site collections created in the past one Month. 

Solution: Get SharePoint Site Collection Created Date using PowerShell! There is no UI to view site creation date in SharePoint! But you can get site creation date in SharePoint using PowerShell as:
Write-host (Get-SPSite "http://sharepointsite.com").RootWeb.created

Lets get all sites created in the past one month based on SharePoint site created date using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get all site collections
$SitesColl = Get-SPSite -Limit All

#Get start date of Last Last Month
$LastMonth= (Get-Date).AddMonths(-1)

#Loop through all sites
ForEach($Site in $SitesColl)
 {
    #Check site creation date
    if($Site.RootWeb.created -gt $LastMonth)
     {
        $CreatedDate = $Site.RootWeb.created.toShortDateString()
        Write-Host "$($Site.RootWeb.url) was created on $($CreatedDate)"
     }
  }
Find all Site collections created today:
Unlike above code, lets use one-liner to find all site collections created today:
Get-SPSite -Limit All | ? { $_.RootWeb.Created -eq[DateTime]::Today} | select Url, @{Name="Created";Expression={$_.RootWeb.Created}}

Find Created date of a Subsite:
Similar code applies for finding a subsite's created date.
Get-SPweb "http://portal.crescent.com/credit" | Select @{Name="Created";Expression={$_.Created}}


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, July 8, 2014

How to Create a New Content Database in SharePoint 2013 using PowerShell

Although a content database can accommodate up to 10,000 site collections in SharePoint, its not advisable to use it so, as the recommended size of the content database is < 200 GB in SharePoint 2013. Also, that could introduce Security, Backup-restore issues to affect your SLA.

When you create new site collection in SharePoint, it picks the available database which has room. Lets see How to create new content database for SharePoint.

How to add a content database in SharePoint 2013 from Central Administration site:
  1. Login to SharePoint App/WFE server as a Farm Administrator
  2. Open Central Administration >> Application Management >> Manage content databases 
  3. Click on "Add a content Database" link
  4. On the Add Content Database page:
    • Specify a Web application for the new database.
    • Specify a database server to host the new database
    • Specify the number of sites collections before a warning is issued. By default, this is 9,000. Specify the total number of sites that can be created in the database. By default, this is 15,000.
    • Click  "OK" to add new content database in SharePoint 2013.
How to Create a New Content Database in SharePoint 2013 using PowerShell

That's a straight forward procedure, isn't it?

A Content Database can only be attached to a single Web Application!

Create a New Content Database in SharePoint 2013 using PowerShell
While you can use SharePoint Central Administration to manage some of the things you need to do to with  content databases, PowerShell is the best tool for managing content databases efficiently. Here is how to add new content database with PowerShell:

Syntax:
New-SPContentDatabase -Name <Content-DB-Name> -WebApplication <Web-App-Name or URL>
Here is an example:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables for Database server and Content Database Name
$DatabaseServerName = "YOUR-DB-SERVER"
$DatabaseName = "Hosting_ContentDB_001"
$WebAppName = "SharePoint Hosting"

#Create content database
New-SPContentDatabase -Name $DatabaseName -DatabaseServer $DatabaseServerName -WebApplication $WebAppName -MaxSiteCount 100 -WarningSiteCount 80

This cmdlet should emit the newly created content database GUID something like:
Id       : faca5154-3c10-4db8-8677-a863b4fc6302
Tips: you cannot have one site collection spread over multiple content databases. But one content database can hold multiple site collections.

Tail: How to create a site collection in a specific Content Database?
If you want to create a new site collection in the new database then there are different options available in the SharePoint 2013. Here is my preferred way: You can create a new site collection in a specific content database by using PowerShell cmdlet New-SPSite cmdlet with -ContentDatabase  parameter. Here is how:
New-SPSite http://your-web-app-url/sites/Your-Site-collection -OwnerAlias "SiteOwnerUserName" -ContentDatabase "ContentDatabaseName" -Name "Site-Name" -Description "Site-Description" -Template "STS#0"
Please note that the "ContentDatabaseName" must refer to an existing database created already.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


How to Change Logo in SharePoint 2013

As a branding initiative, The first thing people do to customize SharePoint site is: changing logos to their company logo. Here is how to change logo in SharePoint 2013:
  1. Navigate to the Site Settings Page by clicking "Site Settings" link from settings gear.
    sharepoint site logo change
  2. Under the "Look and Feel" section, click on "Title, description, and icon" link. 
    sharepoint 2013 custom logo
  3. Select the logo either from your computer ( When insert from computer, the logo will be upload to "Site Assets" library.) or from any SharePoint library.
    sharepoint 2013 insert logo from computer
  4. Optionally, You can enter Logo description. Click OK to apply your new logo. You can copy the logo file to your each WFE, so that the logo will be retrieved from file system rather from a SharePoint library of a site collection
and the result of SharePoint 2013 change logo URL:
sharepoint 2010 add logo to site
Tips: Keep the logo background transparent so that it can match on any color theme!
That's all!

 

FAQS on SharePoint Logo:


SharePoint 2010 logo change
The same procedure applies to SharePoint 2010 also to set site logo.
sharepoint 2010 change logo

SharePoint 2013 change site logo programmatically
You can set: SiteLogoUrl property of the SPWeb Object to change site logo programmatically in SharePoint. Here is how:
SPSite.RootWeb.SiteLogoUrl = "Logo-URL"; //such as:"/_layouts/15/images/CustomLogo.png" or "/sites/operations/siteassets/CustomLogo.png"
We are setting the Root Web's logo property to inherit site logo on all of its sub sites.

SharePoint 2010/2013 change logo for all sites
Out-of-the-box there is no shortcut, But these tricks will do: SharePoint 2013 default site logo URL is: "/_layouts/15/images/siteIcon.png", for SharePoint 2010, SharePoint 2013 logo location at: "/_layouts/images/siteIcon.png". The "Images" folder is a virtual folder mapped to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\IMAGES" in the SharePoint web front end servers.
sharepoint 2013 logo location
So, the trick is: Take a backup of the logo file "SiteIcon.png" and replace your logo with the same name! Much cleaner approach will be: Set logo using PowerShell.


Set SharePoint 2010 Logo URL using PowerShell
Lets change logo for all sites in the entire farm - which includes all sub-sites from all web applications.
Get-SPWebApplication | Get-SPSite | Get-SPWeb |  foreach { " Changing Logo for:" $_.Url; $_.SiteLogoUrl="/_layouts/images/your-logo.png" }
Read more at: SharePoint 2013 Change Site Logo Programmatically with PowerShell

SharePoint 2010 add logo to feature:
You can pack and deploy your custom logo as part of SharePoint solution package.

I changed the logo, but still getting the old logo. This could be because of the browser cache. Try hitting Control+F5 keys. Quick fix: Change the logo image file name in 12/14/15 hive and run the PowerShell code to apply new logo image!

Getting repeated authentication prompt after changing logo: Your logo file in 15 hive or library is not inheriting permissions. Go to the properties of the file and inherit permissions to fix this issue. This could also happens when Logo file is stored in SharePoint libraries - Make sure users have read access at least! and it should be approved (if content approvals is enabled!), checked-in and published!

Web part Pages doesn't display New Logo:
Well, its a known issue and find the solution at: Fix Custom SharePoint 2010 Logo Missing in Web Part Pages

SharePoint 2010 logo not displaying
SharePoint site logo not displaying, instead it gives red x in the place of logo. This happens when SharePoint site logo path is not valid!  Right click on the broken site logo image, Copy-Paste the URL of the image, verify that the logo path is correct.
sharepoint 2013 logo not displaying red x

Make SharePoint 2010 logo link root site
By default, on clicking the site logo, it takes us to the root of the current site. Its possible to change the logo hyperlink. Here is how: Make SharePoint Site Logo Link Point to Root Site Collection

SharePoint 2010 master page logo
You can change logo from SharePoint 2013 master page level also. Locate the element: <SharePoint:SiteLogoImage> and you can change the Logo Image URL attribute of it.

 SharePoint2013 hide logo
To remove logo from SharePoint 2013 sites, we can make it hidden with this style:
.s4-titlelogo > a > img{
visibility: hidden;
}
To remove any custom logo, simply clear the logo URL already set!

SharePoint logo size
The default size of the SharePoint 2013 logo is: 180x64 pixels. But SharePoint 2013 changes this size according to your logo size. To increase logo size simply resize your SharePoint 2013 logo with Photoshop or any other relevant tool. To change logo size (width and height) in CSS, use this styles:
.s4-titlelogo > img, .s4-titlelogo > a > img { width: 150px;height: 150px;}


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...