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

SharePoint 2013 Change Site Logo Programmatically with PowerShell

$
0
0

Although, We can change SharePoint 2013 site logo by going to : Site Settings >> "Title, description and icon" URL by SharePoint web user interface, Lets change logo for all sites in a site collection
through PowerShell to save some time.

SharePoint 2013 change site logo programmatically using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

#Web URL to update Logo
$WebURL = "http://sharepoint.crescent.com/sites/operations/us/"

#Get the Web
$Web = Get-SPWeb $WebURL

$web.SiteLogoUrl = "/_layouts/15/images/sharepoint-diary-logo.png" #can be from any library too: "/sites/operations/images/Corp-Logo.png"
$web.Update()

Write-host "Logo updated for :"$WebURL
This script changes logo programmatically for a single site.

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. The "Images" virtual folder is mapped with "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\IMAGES" in the file system.

Make sure your logo file is accessible by everyone. Users must have read access at least! and it should be approved (if content approvals is ON. Checked-in and published too!). Otherwise, your users may end-up continuous authentication prompts without page loading, when accessing SharePoint sites!

SharePoint 2010 update logo URL using PowerShell for a Site collection:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

$SiteURL = "http://Your-Site-Collection-URL"

#Get the site collection
$Site = Get-SPSite $SiteURL

#Iterate through each site in the site collection
foreach($web in $Site.AllWebs)
{
#sharepoint change logo programmatically
$web.SiteLogoUrl = "/relative-path-logo-file"
$web.Update()
}
This script makes the change in logo for all sites in SharePoint 2010 (or SharePoint 2013).

SharePoint PowerShell Change Site logo for All sites in a Web Application: 
Lets change logo for entire web application in one liner:

#sharepoint 2010/2013 change logo for all sites

Get-SPWebApplication "http://sharepoint.crescent.com" | Get-SPSite -Limit "All" | Get-SPWeb -Limit "All" | foreach { $_.SiteLogoUrl=""; $_.update(); Write-host "Changing Logo for:"$_.Url; }

All of these scripts are valid for SharePoint 2010 also!

The filtering process could not be initialized. Verify that the file extension is a known type and is correct

$
0
0
On analyzing SharePoint search crawl logs, found many instances of the error: "The filtering process could not be initialized. Verify that the file extension is a known type and is correct"
The filtering process could not be initialized. Verify that the file extension is a known type and is correct
Root cause:
This is because, SharePoint server 2007 search crawler doesn't recognize Office 2010 file types (such as .docx, .pptx, .xlsx,etc).

Solution: Download and Install Office 2010 Filter pack from http://www.microsoft.com/en-us/download/details.aspx?id=17062 to the Index server.
 
This filter pack installs few dlls and fixes the above issue. If you happen to see this error on PDF documents, make sure you have PDF IFilters installed and configured.

Change Quick Launch Width in SharePoint 2013/2010/2007

$
0
0
When using lengthy titles in SharePoint 2013 quick launch bar, we may have to increase the width to fit the contents without wrapping to next line. Here are the nifty collection of CSS styles to change the width of left navigation in SharePoint.

SharePoint 2013 left navigation width:
<style type="text/css">
/*increase quick launch width */
#sideNavBox
{
width:250px;
}

/*Middle Content */
#controlbox{
margin-left: 280px;
}

</style>

SharePoint 2010 increase quick launch width:
<style type="text/css">
/*sharepoint 2010 change left navigation width*/
#s4-leftpanel
{
width:180px;
}

/*Middle Content */
.s4-ca {
margin-left: 200px;
}

</style>

Change SharePoint 2007 quick launch width:

<style type="text/css">
/*sharepoint quick launch column width*/
.ms-quicklaunchouter
{
width:150px!important;
}
</style>
All of these SharePoint quick launch width changing CSS codes can be from SharePoint theme CSS file, Alternate CSS, placed in CEWP , Master page, Web Part page edited with SharePoint designer 2010 to increase quick launch width.

Here is the Before and after screens:
Before changing SharePoint 2013 left navigation width
sharepoint 2010 change width of quick launch
 After change width of left navigation:
 sharepoint 2013 increase quick launch width

Change SharePoint 2013/2010 Site Logo Link to Root Site URL

$
0
0
By default, on clicking the SharePoint 2010 or SharePoint 2013 site logo - It takes us to the root of the current site or sub-site. But you may want to link logo to top level site.Well, to change this behavior you got to change the master page.
Important: Since this is a Master page change, You have to apply the updated master page to all site collections for the changes to take effect!

Set SharePoint 2010 logo link root site:
  • Open your Master page in SharePoint Designer 2010, Locate the below line:
<SharePoint:SPLinkButton runat="server" NavigateUrl="~site/" id="onetidProjectPropertyTitleGraphic">
  • Replace the ~site value with ~sitecollection .Save and close the master page (approve and publish, if required!) . This changes SharePoint 2010 logo link to root site collection.
    change sharepoint 2010 logo link URL
In SharePoint 2013 - Change site logo link URL:
  • Open your SharePoint 2013 site in SharePoint designer 2013, Edit the master page in "Advanced Edit Mode",
  • Locate the following code :
<SharePoint:SPSimpleSiteLink CssClass="ms-siteicon-a" runat="server" id="onetidProjectPropertyTitleGraphic" >
<SharePoint:SiteLogoImage CssClass="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl="/_layouts/15/images/siteIcon.png?rev=23" runat="server"/>
</SharePoint:SPSimpleSiteLink>
  • Replace the control <SharePoint:SPSimpleSiteLink> with <SharePoint:SPLinkButton> and add the "NavigateUrl="~sitecollection/" attribute to it.Here is the modified code:
<SharePoint:SPLinkButton NavigateUrl="~sitecollection/" CssClass="ms-siteicon-a" runat="server" id="onetidProjectPropertyTitleGraphic" >
<SharePoint:SiteLogoImage CssClass="ms-siteicon-img" name="onetidHeadbnnr0" id="onetidHeadbnnr2" LogoImageUrl="/_layouts/15/images/siteIcon.png?rev=23" runat="server"/>
</SharePoint:SPLinkButton >
This changes logo link URL pointing from current site to Root Site!
change sharepoint 2013 logo link

Export SharePoint 2007 Search Crawl Log Errors using PowerShell

$
0
0
Requirement: Found so many errors logged in the Search crawl log. Wanted to analyze them.

Solution: Lets use this PowerShell Script to export search crawl errors to CSV:
 #Load SharePoint Assemblies
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search")

#Web Application URL
$url = "http://sharepoint.crescent.com"
$csID = 4 #Content source id - Local SharePoint sites

#Objects to get Crawl History
$site = new-Object Microsoft.SharePoint.SPSite($url);
$context = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($site);
$logViewer = new-object Microsoft.Office.Server.Search.Administration.logviewer ($context)

$crawlLogFilters = New-Object Microsoft.Office.Server.Search.Administration.CrawlLogFilters

$EndDate = [System.DateTime]::Now
$StartDate=$endDate.AddDays(-1)

#Content Source Id
$csProp=[Microsoft.Office.Server.Search.Administration.CrawlLogFilterProperty]::ContentSourceId
$crawlLogFilters.AddFilter($csProp, $csID)
#Get all Errors
$crawlLogFilters.AddFilter([Microsoft.Office.Server.Search.Administration.MessageType]::Error)
#Add Start Date and End Date
$crawlLogFilters.AddFilter($startDate, $endDate)

$startNum = 0
$errorItems += $logViewer.GetCurrentCrawlLogData($crawlLogFilters, ([ref] $startNum))

while($startNum -ne -1)
{
$crawlLogFilters.AddFilter(“StartAt”, $startNum)
$startNum = 0;
$errorItems += $logViewer.GetCurrentCrawlLogData($crawlLogFilters, ([ref] $startNum))
#Write-Host "Processing $startNum";
}

$errorItems | Export-CSV "d:\Backup\crawllog.csv" -notypeinformation

How to Change Logo in SharePoint 2013

$
0
0
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;}

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

$
0
0
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!

Download All Document Versions using Web Services - PowerShell

$
0
0
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.

# ******* Variables Section ******************
#Define these variables
$WebURL="http://sharepoint.crescent.com/sites/Operations/"
$FilePath ="http://sharepoint.crescent.com/sites/Operations/docs/designDoc.txt"
$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)"
}

How to Integrate Twitter with SharePoint to Get Twitter Feeds

$
0
0
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 “Source Editor”, 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

Export SharePoint List Item Version History to Excel

$
0
0
I wrote a PowerShell script and C# object model codes to generate SharePoint version history report in SharePoint document version history report, related to that, got a new requirement to export version history to excel.

This version history report helps to compare what data is changed, who changed the list data, etc over time.  just replace the values of WebURL, ListName variables with your Site/List values and run the script to export version history SharePoint 2013.

Here is the PowerShell script for SharePoint version history export to excel:
# ******* Variables Section ******************
#Define these variables
$WebURL="http://sharepoint.crescent.com/sites/Sales/"
$ListName ="Invoice"
$ReportFile = "D:\Invoice_VersionHistory.csv"
# *********************************************

#delete file if exists
If (Test-Path $ReportFile)
{
Remove-Item $ReportFile
}

#Get the Web and List
$Web = Get-SPWeb $WebURL
$List = $web.Lists.TryGetList($ListName)

#Check if list exists
if($List -ne $null)
{
#Get all list items
$ItemsColl = $List.Items

#Write Report Header
Add-Content -Path $ReportFile -Value "Item ID, Version Lable, Created by, Created at, Title"

#Loop through each item
foreach ($item in $ItemsColl)
{
#Iterate each version
foreach($version in $item.Versions)
{
#Get the version content
$VersionData = "$($item.id), $($version.VersionLabel), $($version.CreatedBy.User.DisplayName), $($version.Created), $($version['Title'])"
#Write to report
Add-Content -Path $ReportFile -Value $VersionData
}
}
}
Write-Host "Version history has been exported successfully!"

Please note, in Line number 25 and 36, I've added only "Title" field from the list. You may want to add additional fields as per your requirement. on running the script, all list item versions will be exported to excel (CSV format).

To export SharePoint document version history, Refer: Extract and Download all document versions

Installing and Configuring ADFS Integration with SharePoint 2013 - Step by Step Guide

$
0
0
Introduction:
Active directory federation services is the solution for extending enterprise identity beyond corporate firewall. It simplifies sharing identities between trusted partners across organizations. Its a common requirement in a typical business scenario, users in one organization wants to access a secured application/website from an another organization. Without ADFS, we'd end-up re-creating user logins for the partner company in our AD. But that introduces the problem of maintaining and managing two separate identities for the partner company users. Here is where ADFS comes to the picture. It solves the problem by federating identities and establishing single sign-on capability. SharePoint 2013 - ADFS integration is seamless as its natively supported.

Generally, in SharePoint world, ADFS is used in these three scenarios:
  1. Domains which are not part of your AD forest  (Such as acquired companies without trusts established, with network connectivity between them in place): User in one organization accesses an application in another organization, so that you can collaborate across organizational boundaries. Say for E.g. Your company is running an internal SharePoint site/application and your partner company/acquired company wants to make use of the same.  across organizational boundaries without duplicating user logins.
  2. Extranet setups for partners/customers - Accessing SharePoint application via the Internet, which extends the first scenario to include remote Internet access who are outside the organization. The external domain is still responsible for validate provided credentials and pass it on the SharePoint.
  3. Office 365/Cloud - You are running a SharePoint farm either in Cloud or in Office 365 and want to provide access to the users of your company without re-creating their identities in the cloud.
How the ADFS - SharePoint authentication process works?
  • User types SharePoint site URL and picks the relevant authentication provider from the sign-in page
  • SharePoint redirects to the respective ADFS server configured already, User promoted for credentials.
  • ADFS handles the authentication by Verifying the provided user name and password from the identity provider - AD
  • ADFS creates a Token, Signs and puts it in a cookie. Redirects to SharePoint with that cookie
  • SharePoint STS validates and extracts the claims from the token
  • SharePoint performs authorization and connects the user to the web application.

There are Three steps involved in integrating ADFS with SharePoint 2013:
  1. Install ADFS Server
  2. Create a trusted relying party for SharePoint 2013 in ADFS
  3. Configure SharePoint 2013 to trust ADFS

Prerequisites:
There are certain prerequisites to be addressed for ADFS SharePoint 2013 configuration.
  1. SSL Certificates: Obtain SSL certificates for your SharePoint 2013 web application, and at least two certificates for ADFS Service communication and for ADFS token signing of 2048-bits.
  2. Default Web Site in IIS - Make sure, in your ADFS Server, the default web site is running in IIS. This site to be SSL enabled with ADFS communication certificate.
  3. SharePoint Web Application requirements: Your web app must be SSL enabled and  authentication mode must be "Claims Based" - which is default in SharePoint 2013. Security Token Service must be up and running.
  4. DNS Entries: Make sure DNS entries (or host file entries, at least!) are created for both SharePoint and ADFS servers, So that both ADFS and SharePoint can identify and communicate between them selves.
  5. Service account - Have a dedicated service account for ADFS service - Must be a Local Admin account and SPN to be set on the service account: setspn -a host/adfs.crescent.com crescent\AdfsSvc
Here is our environment setup:
In production environments, ADFS infrastructure is created as a separate farm with ADFS Proxy server. For evaluation purpose, I'm using below configurations:
  • ADFS Server - ADFS.Crescent.com
  • SharePoint Farm - Web Application: Intranet.Crescent.com  
  • Certificates 
    • Intranet.Crescent.com - SharePoint web application certificate
    • ADFS.Crescent.com - Certificate for ADFS server to communicate securely.
    • TokenSigning.Crescent.com - ADFS Token signing certificate.

 

Step 1: Install ADFS Server Instance

In windows server 2008 R2, ADFS 2.0 was available as a separate download, But windows Server 2012 is built-in with ADFS capability. So, all you have to do is: Add AD FS server role by running the "Add server role wizard!". ADFS Server can be installed as a standalone or as a ADFS farm with multiple servers.  if standalone, it uses "Windows Internal database", SQL Server is used otherwise.
Although its possible to have the ADFS server in Same SharePoint box, Microsoft doesn't recommends it.

Lets begin installing ADFS Server role.
  1. Login to your proposed ADFS server. Make sure its already joined to the AD Domain. Open Server Manager
  2. Click on "Add roles and features" link from Dashboard section of the Server Manager.
  3. You'll be presented with "Add Roles and Features Wizard" . Click "Next" to start
  4. Choose "Role-based or feature-based installation" on installation Type and click "Next"
  5. Select the appropriate Server in server selection
  6. Check "Active Directory Federation Services" Server Roles and click "Next"
  7. In Features page, Make sure ".Net Framework 3.5" is already installed. if not, Select that check box.
  8. Click "Next" on AD FS page
  9. Choose "Federation Service" under Role Services section
  10. Click on "Install" button to start installing ADFS Server role.
  11. Wait for the installation to complete. Click on "Close" button to exit from the wizard.
Configure ADFS Server:
  1.  Go to Server Manager, Click on "AD FS" tab. There will be a notification at the top saying "Configuration required for Federation service". Click on "More" link, that pops up a message.
  2. Click on "Run the AD FS Management snap-in" link to run Post-deployment configuration wizard.
  3.  Now, we got into ADFS snap-in. Click on "AD FS Federation Server configuration Wizard" link to start configuring ADFS.
  4. Choose "Create a new Federation Service" option in welcome screen.
  5. Select the deployment type as "Stand-alone Federation Server"
  6. Choose the appropriate SSL Certificate for ADFS communication
  7. Click "Next" on the summary page
  8. Wait for the AD FS configuration to complete.
Verify ADFS installation:
Try navigating to any of the below URL. You should get a XML file.
  • https://YourADFS-Server.com/adfs/ls/IdpInitiatedSignon.aspx
  • https://<<servername>>/FederationMetadata/2007-06/federationmetadata.xml

 

Step 2: Create trusted relying party in ADFS 

Now, the next step is to add new trusted relying party (in our case, its our SharePoint site URL). We'll have to set up ADSFS to allow our SharePoint web sites as a Relying Parties so that SharePoint will consume claims from ADFS server.

Configure ADFS for SharePoint 2013:
Lets Add SharePoint Web Application URL as a Trusted Relying Party:
  1. Go to Server Manager, Click on "AD FS Management" from tools menu.
  2. From AD FS snap-in, Click on "Required: Add a trusted replying party" link. You can also click on "Add Relying party Trust" to get the same.
  3. Click "Start" button to initiate relying party trust wizard.
  4. In "Select Data Source" tab, choose "Enter data about the relying party manually" and click "Next"
  5. Give a display name to the relying party.
  6. Choose profile as "AD FS Profile"
  7. Token signing certificate is optional. So, we can skip it by pressing "Next" button
  8. Here is an important step: Configure URL! Select "Enable support for the WS-Federation Passive protocol" check-box. Enter the relying party WS-Federation passive protocol URL by appending : /_trust/ with your SharePoint web application. In my case, My web application is: https://intranet.crescent.com. So, I'm entering:  https://intranet.crescent.com/_trust/
  9. Configure identifiers: Enter the relying party trust identifier. It uses the naming convention of : URN:Your-Web-App. Lets enter "urn:intranet:crescent" and click on "Add" button
  10. For issuance authorization rules, choose "Permit all users to access this relying party" and click Next.
  11. Click "Next" on the summary page.
  12. Enable "Open the Edit Claim Rules dialog for this relying party trust when the wizard closes" check box, and click on "Close" button.
Edit Claims Rule:
SharePoint Claims-based authentication - authenticates users based on these set of claims, such as User principle name, E-Mail address, etc.
  1. Click on "Add Rules" button in Edit Claim Rules window.
  2. Choose the Claim rule template as: "Send LDAP Attributes as Claims"
  3. Give a Name to your claim rule, Choose the attribute store as "Active Directory", Map the attributes to be sent to SharePoint from Active Directory via ADFS. I've selected "Email-Addresses" with "E-Mail Address" and "User-Princila-Name" with "UPN". Click "Finish" button once done.
Repeat the relying party wizard for all of your web applications.

Change the Token Signing Certificate in ADFS Server
We must have different SSL certificates for "ADFS communication certificate" , "ADFS token signing certificate". we have to disable the AD FS automatic certificate rollover feature to add a token signing certificate.
Open PowerShell on the Federation Server (VSrvFs) and run the following command:
Set-ADFSProperties -AutocertificateRollover $false
Now, from the ADFS console Service >> Certificates >> Add Token-Signing Certificate >> You'll be prompted with a menu to choose a certificate >> Select the "TokenSigning.crescent.com" certificate and mark it as primary.

Remember, You must export this ADFS token signing certificate to all SharePoint servers to establish trust.

Private Key Permissions:
The service account needs to have "Read" permissions at least on the private key of the Token signing certificate. From the certificates snap-in, Browse to personal >> certificates. Right click Your token signing certificate > All Tasks > Manage Private Keys >> Grant "Read" permission to the service account 

Export this ADFS token signing certificate to all SharePoint server(s)

ADFS Token signing certificate must be exported from ADFS server and used while creating trust in  SharePoint Server. Here is how:
  1. From ADFS console, Expand "Certificates" folder, Right Click on your ADFS token signing certificate and choose "View Certificate".
  2. Under the "Details" tab, Click on "Copy to file" button. 
  3. For Export Private key section, choose "No, do not export the private key"
  4. Click "Next". Choose export file format as "DER Encoded binary x.509 (.CER)"
  5. This will export the certificate from ADFS. 

 

Step 3: Configure SharePoint 2013 to Trust ADFS

As a final step, Lets create a trusted identity token issuer pointing to ADFS as the claims provider, using PowerShell

Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

#Register the Token Signing certificate from ADFS Server to establish Trust between SharePoint and ADFS server
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\ADFS.TokenSigning.cer")
New-SPTrustedRootAuthority -Name "ADFS Token Signing Certificate" -Certificate $cert

#Map the claims attributes
$EmailMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming

$UPNMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" -IncomingClaimTypeDisplayName "UPN" -SameAsIncoming

$realm = "urn:intranet:crescent"

#Sign-in URL will be ADFS Server instance
$signInURL="https://adfs.crescent.com/adfs/ls"

#Create new trusted identity token issuer
$TrustedIdentity = New-SPTrustedIdentityTokenIssuer -Name "Crescent.com" -Description "ADFS Trusted users from Crescent.com Domain" -realm $realm -ImportTrustCertificate $cert -ClaimsMappings $EmailMap,$upnMap -SignInUrl $signInURL -IdentifierClaim $Emailmap.InputClaimType
The first two lines of the above code, registers the certificate in SharePoint certificate store. Moreover, You may have to do this for Root Certificate Authority as well. You can see them under "Manage Trusts" link in security section of central administration.

Realm - is a identifier which helps ADFS to load respective configuration for a particular profile. which uses the convention of: urn:yourwebapp:yourdomain (can be anything, technically. It just uniquely identifies between multiple web applications)

IdentifierClaim - is the unique ID that identifies users in SharePoint. So,when users logged in via ADFS, they'll be identified by Email id in this case. Also, when granting access to SharePoint sites from ADFS, we'll have to use this identifier as user names. Make sure that the mapped claims exists in the source. E.g. If E-mail is mapped as Identifierclaim, then It must be exists in AD. In other worlds, E-mail field must contain a value, shouldn't be null!

SharePoint 2013 ADFS with multiple web applications 
So, You have established trusted identity provider for your primary web applications, and all other  web apps as well, say for e.g. My sites. Now, You'll have to add them in your trusted identity provider with this PowerShell code:
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

$TrustedIdentifyProvider = Get-SPTrustedIdentityTokenIssuer "Crescent.com"

$uri = New-Object System.Uri("https://mysites.crescent.com/")

$TrustedIdentifyProvider.ProviderRealms.Add($uri, "urn:mysite:crescent")

$TrustedIdentifyProvider.Update()

Configure SharePoint Web Application:
Next step is to enable ADFS claims in SharePoint. 
  • Go to Central Administration > Application Management > Manage Web Applications.
  • Click on "Authentication Providers" button from the ribbon
  • Select the "Default" link from the list
  • Scroll down and pick the authentication provider we just created.
  • Click "Ok" to save your changes.

Grant ADFS users Permission to the SharePoint web application
When you add permission for the user in SharePoint you have to add it as the IdentifierClaim (for example if the identifier is the email - you should add the user as user@contoso.com from SharePoint side and login with Domain\userName format.). If you skip this step, users from ADFS will get: access denied!

and when users hit SharePoint URL, They'll be presented with the default sign-in page
Troubleshooting?
Errors? Event log is the best place to start debugging!.

jQuery Image Rotator for SharePoint

$
0
0
Here is the quick and simple way to implement rotating image slider for SharePoint using jQuery.All you have do is: upload slider images to any SharePoint library and change the image paths in Slider section of the below code and place it in content editor web part or Script editor in SharePoint 2013:

jQuery Rotating Banner code:
<div class="im-brand-central-slider">
<ul class="slider">
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/Growth.jpg" /></li>
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/ImproveTechOutcomes.jpg" /></li>
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/NewEyes.jpg" /></li>
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/NextGeneration.jpg" /></li>
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/PeopleAreKey.jpg" /></li>
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/Realize.jpg" /></li>
</ul>
<div class="slider-nav">
<a href="javascript:void(0)" class="slider-prev">Prev</a>
<a href="javascript:void(0)" class="slider-next">Next</a>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
(function ($) {
"use strict";
var ver = 'Lite-1.7';
var msie = /MSIE/.test(navigator.userAgent);
$.fn.cycle = function (options) {
return this.each(function () {
options = options || {};

if (this.cycleTimeout)
clearTimeout(this.cycleTimeout);

this.cycleTimeout = 0;
this.cyclePause = 0;

var $cont = $(this);
var $slides = options.slideExpr ? $(options.slideExpr, this) : $cont.children();
var els = $slides.get();
if (els.length < 2) {
if (window.console)
console.log('terminating; too few slides: ' + els.length);
return; // don't bother
}

// support metadata plugin (v1.0 and v2.0)
var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null;
if (meta)
opts = $.extend(opts, meta);

opts.before = opts.before ? [opts.before] : [];
opts.after = opts.after ? [opts.after] : [];
opts.after.unshift(function () { opts.busy = 0; });

// allow shorthand overrides of width, height and timeout
var cls = this.className;
opts.width = parseInt((cls.match(/w:(\d+)/) || [])[1], 10) || opts.width;
opts.height = parseInt((cls.match(/h:(\d+)/) || [])[1], 10) || opts.height;
opts.timeout = parseInt((cls.match(/t:(\d+)/) || [])[1], 10) || opts.timeout;

if ($cont.css('position') == 'static')
$cont.css('position', 'relative');
if (opts.width)
$cont.width(opts.width);
if (opts.height && opts.height != 'auto')
$cont.height(opts.height);

var first = 0;
$slides.css({ position: 'absolute', top: 0 }).each(function (i) {
$(this).css('z-index', els.length - i);
});

$(els[first]).css('opacity', 1).show(); // opacity bit needed to handle reinit case
if (msie)
els[first].style.removeAttribute('filter');

if (opts.fit && opts.width)
$slides.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$slides.height(opts.height);
if (opts.pause)
$cont.hover(function () { this.cyclePause = 1; }, function () { this.cyclePause = 0; });

var txFn = $.fn.cycle.transitions[opts.fx];
if (txFn)
txFn($cont, $slides, opts);

$slides.each(function () {
var $el = $(this);
this.cycleH = (opts.fit && opts.height) ? opts.height : $el.height();
this.cycleW = (opts.fit && opts.width) ? opts.width : $el.width();
});

if (opts.cssFirst)
$($slides[first]).css(opts.cssFirst);

if (opts.timeout) {
// ensure that timeout and speed settings are sane
if (opts.speed.constructor == String)
opts.speed = { slow: 600, fast: 200 }[opts.speed] || 400;
if (!opts.sync)
opts.speed = opts.speed / 2;
while ((opts.timeout - opts.speed) < 250)
opts.timeout += opts.speed;
}
opts.speedIn = opts.speed;
opts.speedOut = opts.speed;

opts.slideCount = els.length;
opts.currSlide = first;
opts.nextSlide = 1;

// fire artificial events
var e0 = $slides[first];
if (opts.before.length)
opts.before[0].apply(e0, [e0, e0, opts, true]);
if (opts.after.length > 1)
opts.after[1].apply(e0, [e0, e0, opts, true]);

if (opts.click && !opts.next)
opts.next = opts.click;
if (opts.next)
$(opts.next).unbind('click.cycle').bind('click.cycle', function () { return advance(els, opts, opts.rev ? -1 : 1); });
if (opts.prev)
$(opts.prev).unbind('click.cycle').bind('click.cycle', function () { return advance(els, opts, opts.rev ? 1 : -1); });

if (opts.timeout)
this.cycleTimeout = setTimeout(function () {
go(els, opts, 0, !opts.rev);
}, opts.timeout + (opts.delay || 0));
});
};

function go(els, opts, manual, fwd) {
if (opts.busy)
return;
var p = els[0].parentNode, curr = els[opts.currSlide], next = els[opts.nextSlide];
if (p.cycleTimeout === 0 && !manual)
return;

if (manual || !p.cyclePause) {
if (opts.before.length)
$.each(opts.before, function (i, o) { o.apply(next, [curr, next, opts, fwd]); });
var after = function () {
if (msie)
this.style.removeAttribute('filter');
$.each(opts.after, function (i, o) { o.apply(next, [curr, next, opts, fwd]); });
queueNext(opts);
};

if (opts.nextSlide != opts.currSlide) {
opts.busy = 1;
$.fn.cycle.custom(curr, next, opts, after);
}
var roll = (opts.nextSlide + 1) == els.length;
opts.nextSlide = roll ? 0 : opts.nextSlide + 1;
opts.currSlide = roll ? els.length - 1 : opts.nextSlide - 1;
} else {
queueNext(opts);
}

function queueNext(opts) {
if (opts.timeout)
p.cycleTimeout = setTimeout(function () { go(els, opts, 0, !opts.rev); }, opts.timeout);
}
}

// advance slide forward or back
function advance(els, opts, val) {
var p = els[0].parentNode, timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
opts.nextSlide = opts.currSlide + val;
if (opts.nextSlide < 0) {
opts.nextSlide = els.length - 1;
}
else if (opts.nextSlide >= els.length) {
opts.nextSlide = 0;
}
go(els, opts, 1, val >= 0);
return false;
}

$.fn.cycle.custom = function (curr, next, opts, cb) {
var $l = $(curr), $n = $(next);
$n.css(opts.cssBefore);
var fn = function () { $n.animate(opts.animIn, opts.speedIn, opts.easeIn, cb); };
$l.animate(opts.animOut, opts.speedOut, opts.easeOut, function () {
$l.css(opts.cssAfter);
if (!opts.sync)
fn();
});
if (opts.sync)
fn();
};

$.fn.cycle.transitions = {
fade: function ($cont, $slides, opts) {
$slides.not(':eq(0)').hide();
opts.cssBefore = { opacity: 0, display: 'block' };
opts.cssAfter = { display: 'none' };
opts.animOut = { opacity: 0 };
opts.animIn = { opacity: 1 };
},
fadeout: function ($cont, $slides, opts) {
opts.before.push(function (curr, next, opts, fwd) {
$(curr).css('zIndex', opts.slideCount + (fwd === true ? 1 : 0));
$(next).css('zIndex', opts.slideCount + (fwd === true ? 0 : 1));
});
$slides.not(':eq(0)').hide();
opts.cssBefore = { opacity: 1, display: 'block', zIndex: 1 };
opts.cssAfter = { display: 'none', zIndex: 0 };
opts.animOut = { opacity: 0 };
opts.animIn = { opacity: 1 };
}
};

$.fn.cycle.ver = function () { return ver; };

// @see: http://malsup.com/jquery/cycle/lite/
$.fn.cycle.defaults = {
animIn: {},
animOut: {},
fx: 'fade',
after: null,
before: null,
cssBefore: {},
cssAfter: {},
delay: 0,
fit: 0,
height: 'auto',
metaAttr: 'cycle',
next: null,
pause: false,
prev: null,
speed: 1000,
slideExpr: null,
sync: true,
timeout: 4000
};

})(jQuery);
jQuery(document).ready(function ($) {
$('ul.slider').cycle({
prev: $('.slider-prev'),
next: $('.slider-next')
});
});
</script>
<style>
.im-brand-central-slider .slider-nav {
width: 685px;
background: #000;
color: #fff;
font-size: 11px;
padding: 3px 0px;
text-transform: uppercase;
font-family: Verdana, Arial, Helvetica, sans-serif;
text-align: right;
}
.im-brand-central-slider .slider-nav a {
cursor: pointer;
color: #f0f0f0 !important;
}
.im-brand-central-slider .slider-nav a:hover{
color: #ffffff !important;
}
.im-brand-central-slider .slider-nav a.slider-prev {
border-right: 1px solid #888;
padding-right: 10px;
margin-right: 5px;
}
.im-brand-central-slider .slider-nav a.slider-next {
margin-right: 10px;
}
.im-brand-central-slider,
.im-brand-central-slider ul.slider {
position: relative;
}
.im-brand-central-slider,
.im-brand-central-slider ul.slider,
.im-brand-central-slider ul.slider li {
width: 685px;
height: 200px;
padding: 0;
margin: 0;
}
.im-brand-central-slider {
height: 219px;
margin-bottom: 20px;
}
.im-brand-central-slider ul.slider,
.im-brand-central-slider ul.slider li{
list-style-type: none;
}
.im-brand-central-slider ul.slider li{
display: block;
position: absolute;
top: 0;
left: 0;
}
.im-brand-central-slider ul.slider li img{
width: 100%;
height: auto;
}
</style>

Verified this rotating banner code works in all of the versions of SharePoint, including SharePoint 2007, SharePoint 2010 and in SharePoint 2013.

Rotating banner in SharePoint 2013:
jquery rotating banner sharepoint


Rotating banner in SharePoint 2007:
jquery rotator sharepoint
My other jQuery Banner rotating implementations:

Get User E-mail Address from List Item "Created By" using PowerShell

$
0
0
For a PowerShell automation work, I had to retrieve the Email ID of the user who has created a particular list item. Here is the nifty PowerShell script to retrieve E-mail ID from created by field:


Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

#Function to get User's Email from User ID
Function GetUserEmail($UserValue)
{
#Uservalue: E.g: "1;#user name";
$arr = $UserValue.Split(";#");
$UserID = $arr[0];
$user = $web.SiteUsers.GetById($UserId);
#the above line returns: SPUser Object

return $user.Email
}

$WebURL ="http://sharepoint.crescent.com/SharePointSupport/"
$ListName ="Site Requests"

#Get the Web and List
$Web = Get-SPWeb $WebURL
$list = $web.Lists[$ListName]

#Get an Item by id
$item = $list.GetItemByID(1)

#Get Created by User details
#$item["Author"] Returns something like: 3;#Salaudeen
$CreatorMail = GetUserEmail($item["Author"])

Write-Host $CreatorMail

Same thing can be done in C# also to get user email address programmatically.

SharePoint 2013 Error: Unexpected response from server. The status code of response is '500'. The status text of response is 'System.ServiceModel.ServiceActivationException'.

$
0
0
SharePoint 2013 Search returned an error:
Unexpected response from server. The status code of response is '500'. The status text of response is 'System.ServiceModel.ServiceActivationException'.


In Event logs of SharePoint web front ends, it left an event:
System.ServiceModel.ServiceHostingEnvironment+HostingManager/33228940
Exception: System.ServiceModel.ServiceActivationException: The service '/_vti_bin/client.svc' cannot be activated due to an exception during compilation.


Solution: 
Either increase the Server Memory or Try closing some running applications in the SharePoint WFEs to freed up the memory in server!

You can also try limiting the memory consumption on various services running on the server. Here are some:
  • Limit the search service 
    • Set-SPEnterpriseSearchService -PerformanceLevel Reduced 
  • Limit the NodeRunner.exe's memory (NodeRunner is a SharePoint Search component)
    • Open the configuration file at "C\Program Files\Microsoft Office Servers\15.0\Search\Runtime\1.0\noderunner.exe.config" Locate the node "nodeRunnerSettings" and set the value for "memoryLimitMegabytes" attribute. By default its value is 0 (which means unlimited). Once done, restart SharePoint Search Host Controller process.

It also happens with you try add/update new items to SharePoint 2013 lists:

PowerShell "Exception of type 'System.OutOfMemoryException'"

$
0
0
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

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.

How to Disable Sync button in SharePoint 2013

$
0
0
Sync option in SharePoint 2013 enables users to keep copies in sync between SharePoint libraries and user's local disk. Once Synched, You get the flexibility to edit documents straight from your local machine.

On clicking the "Sync" button from any document library, triggers the client application "SharePoint workspace" - which is a successor of Microsoft Groove.
How to Disable Sync button in SharePoint 2013
In some cases, you may want to disable this option per your company policies. Follow these steps, If you want to disable Sync button in SharePoint 2013:
  • Go to your SharePoint site Settings
  • Click on "Search and Offline Availability" link under "Search" group
  • Choose "No" for "Allow items from this site to be downloaded to offline Clients?". Choosing "Yes" enables the Sync option back.disable sync in SharePoint library
  • Click OK to save your changes.

That's all. This disables Sync option in SharePoint 2013 site level. PowerShell can be utilized to Turn it OFF/ON globally for the entire farm using:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

Get-SPSite -limit all | get-SPWeb -limit all | Foreach { $_.ExcludeFromOfflineClient=1;
$_.Update()} 

You can also enable-disable sync for a particular SharePoint library.
  • Go to Library settings 
  • Click Advanced Settings under the General Settings category.
  • Under Offline Client Availability category, select No to prevent users from download the documents.

Determine the Installed SharePoint Edition: Standard or Enterprise

$
0
0
Here is how to check whether standard or enterprise edition is installed in SharePoint 2013.

Go to Central Admin >> Upgrade and Migration >> Click on "Enable Enterprise Features"
Determine the Installed SharePoint Edition: Standard or Enterprise

This procedure stays same to check standard or enterprise SharePoint 2010 and SharePoint 2007:
  • When the “Enterprise” is selected and grayed-out, it’s an Enterprise edition of SharePoint!
  •  Here is the Standard edition screen: If, Standard option is enabled, then we can determine its a Standard edition.

SharePoint 2013 standard to enterprise upgrade:
You can use this page in SharePoint to upgrade standard to enterprise. But you can't downgrade SharePoint enterprise to standard.

Copy List Permissions in SharePoint using PowerShell

$
0
0
Ever wanted to clone permissions between SharePoint lists or Libraries? Well, Here is the nifty PowerShell script to copy permissions between SharePoint lists:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

#PowerShell Function to copy permissions between Lists in SharePoint
Function Copy-ListPermissions()
{
param(
$WebURL,
$SourceListName,
$TargetListName
)
#Get the Web
$Web = Get-SPweb $WebURL

#Get Source and Target Lists
$SourceList = $Web.lists[$SourceListName]
$TargetList = $Web.lists[$TargetListName]

#if permissions are Inherited in Source, apply it in Target list
if($SourceList.Permissions.Inherited)
{
$TargetList.ResetRoleInheritance()
}
else #Copy permissions from Source to Target List
{
#Reset the Inheritence in Target List
$TargetList.BreakRoleInheritance($false)

#Copy Source list permissions to Destination List
$SourceList.RoleAssignments | foreach-object {
$targetList.RoleAssignments.Add($_)
}
}
$TargetList.Update()
}
#Call the function to copy list permissions
Copy-ListPermissions "http://sharepoint.crescent.com/sites/operations/us" "Documents" "Invoice"
This script copies all users and groups from the source list to target list. Any custom permissions already applied on the target list will be lost!

The above method can be used to copy permissions between SharePoint list items and sites.

Get SharePoint Document Library Inventory with PowerShell

$
0
0
This PowerShell script generates detailed report on the given SharePoint library's inventory in addition with its storage data. The output report contains:
  • File Name
  • File Size(KB)
  • Versions Size(KB)
  • Total File Size(KB)
  • Created on
  • Last Modified
  • Created by
  • Parent Folder
  • URL
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

# Function to retrieve detailed Library storage Report
Function GetLibraryStorageRpt($Folder)
{
#Array to hold Storage data for all files
$StorageDataCollection = @()

$FileSize = 0
$TotalFileSize = 0
foreach ($File in $Folder.Files)
{
#Get File Size
$FileSize = $File.TotalLength

$VersionSize = 0
#Get the Versions Size
foreach ($FileVersion in $File.Versions)
{
$VersionSize +=$FileVersion.Size
}
$TotalFileSize = $FileSize + $VersionSize

$StorageDataResult = New-Object PSObject

$StorageDataResult | Add-Member -type NoteProperty -name "File Name" -value $File.Name
$StorageDataResult | Add-Member -type NoteProperty -name "File Size(KB)" -value $($FileSize/1KB)
$StorageDataResult | Add-Member -type NoteProperty -name "Versions Size(KB)" -value $($VersionSize/1KB)
$StorageDataResult | Add-Member -type NoteProperty -name "Total File Size(KB)" -value $($TotalFileSize/1KB)
$StorageDataResult | Add-Member -type NoteProperty -name "Created on" -value $File.TimeCreated
$StorageDataResult | Add-Member -type NoteProperty -name "Last Modified" -value $File.TimeLastModified
$StorageDataResult | Add-Member -type NoteProperty -name "Created by" -value $File.Author.Name
$StorageDataResult | Add-Member -type NoteProperty -name "Parent Folder" -value $File.ParentFolder.URL
$StorageDataResult | Add-Member -type NoteProperty -name "URL" -value $File.URL

$StorageDataCollection += $StorageDataResult
#Write-Host "Processing File:"$File.Name
}
#Get Files in Sub Folders
foreach ($SubFolder in $Folder.SubFolders)
{
if($SubFolder.Name -ne "Forms") #Leave "Forms" Folder which has List default Aspx Pages.
{
GetLibraryStorageRpt($SubFolder)
}
}
return $StorageDataCollection
}

#Input Variables
$WebURL = "http://sharepoint.crescent.com/sites/operations"
$ListName ="Documents"

#Get the List
$List = Get-SPWeb $WebURL | Select -ExpandProperty "Lists" | Where-Object{$_.Title -eq $ListName}

#Call the function to get data
$StorageDetails = GetLibraryStorageRpt($List.RootFolder)

write-host "Total Number of Files:" $List.ItemCount
write-host "Library Created by:" $List.Author

#Calculate the Total Size
$TotalSize = ($StorageDetails | Measure-Object 'Total File Size(KB)' -Sum | Select -expand Sum)
Write-host "Library Size in MB: "([Math]::Round( ($TotalSize/1024),2))

#Export the data to CSV File
$StorageDetails | sort-object "Total File Size" -descending | Export-csv "$($ListName)_LibraryStroageRpt.csv" -notypeinformation
Write-Host "Storage Report has been Generated!"

Archive SharePoint Library Files into Sub-Folders using PowerShell

$
0
0
Requirement: We've a very large library with more than 20,000 files stored in the root of the document library without any sub-folders. Got to move files into Sub-folders to improve performance.

Solution: We analyzed the library content and decided to move files into sub-folders based on file's created date.

PowerShell script to move files into sub-folders in SharePoint document library:
#Import PowerShell Snap-in
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

#Create a custom function to archive files
Function Archive-Files($WebURL, $ListName)
{
#Get the web and List
$Web = Get-SPWeb $WebURL
$List= $web.Lists[$ListName]

$RootItems = $List.RootFolder.files
Write-host "Total number of files found in the Root: "$RootItems.count

#Move each file in the root folder to archive folder
foreach($item in $RootItems)
{
#Get the File
$file = $Web.GetFile($item.URL)

#Get the Month & Year values from the File's crated date
$MonthYearValue = $file.TimeCreated.ToString('MMM-yyyy')

# Try to Get the Archive Sub-Folder in the target Library
$TargetFolder = $List.ParentWeb.GetFolder($List.RootFolder.Url + "/" +$MonthYearValue);

#If the Archive folder doesn't exist, Create it!
if ($TargetFolder.Exists -eq $false)
{
$TargetFolder = $List.Folders.Add("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $MonthYearValue)
$TargetFolder.Update()
}
#Move the File
$file.MoveTo($TargetFolder.Url + "/" + $File.name)
}
}

#Call the function to Archive Files
Archive-Files "http://sharepoint.crescent.com/sites/marketing/" "Invocies"
This script preserves Metadata, BTW! You can also move files into sub-folders of an another SharePoint library for archival.
Viewing all 1053 articles
Browse latest View live




Latest Images