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

Find All Inactive Features in SharePoint with PowerShell

$
0
0
What is inactive Feature in SharePoint? Well, Features which are installed but not activated anywhere!

Here is the PowerShell script to find inactive features for SharePoint:
Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue

$InactiveFeatures = @()

#Get All installed features on respective scopes
$WebAppFeatures = Get-SPFeature | Where-Object {$_.Scope -eq "WebApplication" }
$siteFeatures = Get-SPFeature | Where-Object {$_.Scope -eq "Site" }
$WebFeatures = Get-SPFeature| Where-Object {$_.Scope -eq "Web" }

Write-host "Checking Web Application Scoped Features..."
foreach ($WebAppFeature in $WebAppFeatures)
{
$Flag = $False
foreach ($WebApp in Get-SPWebApplication)
{
if ((Get-SPFeature -WebApplication $WebApp.URL | Where-Object {$_.Id -eq $WebAppFeature.id}) -ne $null)
{
#We found that the Feature is active, Lets end up the loop
$Flag = $True
break
}
}
if($Flag -eq $False)
{
Write-Host "$($WebFeature.DisplayName) is not Active on any Web Application!)"
}

}

Write-Host "`nChecking Site Collection Scoped Features..."
foreach ($SiteFeature in $SiteFeatures)
{
$Flag = $False
:WebAppLoop1 foreach ($WebApp in Get-SPWebApplication)
{
foreach($site in $WebApp.Sites)
{
if ((Get-SPFeature -Site $Site.URL | Where-Object {$_.Id -eq $SiteFeature.id}) -ne $null)
{
#We found that the Feature is active, Lets end up the loop
$Flag = $True
break WebAppLoop1
}
}
}
if($Flag -eq $False)
{
Write-Host "$($SiteFeature.DisplayName) is not Active on Any Site Collection!"
}
}

Write-host "`nChecking Web Scoped Feature..."
foreach ($WebFeature in $WebFeatures)
{
$Flag = $False
#I'm limiting to a single web application, Remove ""http://sharepoint.crescent.com" to process all WebApps
:WebAppLoop2 foreach ($WebApp in Get-SPWebApplication "http://sharepoint.crescent.com")
{
foreach($Site in $WebApp.Sites)
{
foreach($Web in $Site.AllWebs)
{
if ((Get-SPFeature -Web $Web.URL | Where-Object {$_.Id -eq $WebFeature.id}) -ne $null)
{
#We found that the Feature is active, Lets end up the loop
$Flag = $True
break WebAppLoop2
}
}
}
}
if($Flag -eq $False)
{
Write-Host "$($WebFeature.DisplayName) is not Active on Any Web!"
}
}

Please note: There could be many OOTB features stay Inactive based on the site template we use. So, Use this script to get an insight of your custom features deployed to the SharePoint 2013/SharePoint 2010 environments.

To get a report on features activated on various scopes, refer:

Start SharePoint Search Crawl using PowerShell

$
0
0
For some reasons, SharePoint search crawl scheduled didn't trigger. So I used this PowerShell script and Windows Task scheduler to trigger Incremental crawls.

Start SharePoint Search Full/Incremental Crawl using PowerShell:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#Get the search service application
$SSA = Get-SPEnterpriseSearchServiceApplication -Identity "Search Service Application"

#Get the Local SharePoint sites content source
$ContentSource = $SSA | Get-SPEnterpriseSearchCrawlContentSource -Identity "Local SharePoint sites"

#Check if Crawler is not already running
if($ContentSource.CrawlState -eq "Idle")
{
Write-Host "Starting Incremental Crawl..."
$ContentSource.StartIncrementalCrawl()
#$ContentSource.StartFullCrawl();
#$ContentSource.PauseCrawl()
}
else
{
Write-Host "Another Crawl is already running!"
Write-Host "NAME: ", $ContentSource.Name, " - ", $ContentSource.CrawlStatus
}

Start Incremental Crawl in MOSS 2007 using PowerShell:

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

$ServerContext = [Microsoft.Office.Server.ServerContext]::Default
$context = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($ServerContext)

$SSPContent = new-object Microsoft.Office.Server.Search.Administration.Content($context)
$SSPContentSources = $SSPContent.ContentSources

foreach ($ContentSource in $SSPContentSources)
{
if ($ContentSource.Name -eq "Local Office SharePoint Server sites")
{
Write-Host "NAME: ", $ContentSource.Name, " - ", $ContentSource.CrawlStatus
if ($ContentSource.CrawlStatus -eq [Microsoft.Office.Server.Search.Administration.CrawlStatus]::Idle)
{
Write-Host "Starting Incremental crawl"
$ContentSource.StartIncrementalCrawl();
}
else
{
Write-Host "Another Crawl is already running!"
}
}
}
This was helpful when user came with an requirement to run incremental crawl for each 15 min!

Find SharePoint Site Column Usage - Report

$
0
0
When trying to delete a SharePoint site column, it gave me an alert saying "Site columns which are included in content types cannot be deleted.Remove all references to this site column prior to deleting it." 

PowerShell script to Find and delete a site column from Content type
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$web= Get-SPWeb "http://sharepoint.crescent.com/sites/operations"
$ColumnInternalName = "BranchLocation"

#Get All Content Types
$CTypes = $web.site.rootweb.ContentTypes
foreach($ContentType in $CTypes)
{
$FieldInUse = $ContentType.FieldLinks | Where {$_.Name -eq $ColumnInternalName }

if($FieldInUse -ne $null)
{
Write-Host "Found the Column in Content Type:" $ContentType.Name -ForegroundColor DarkGreen
##To Remove the field from content type, uncomment below two lines
#$ContentType.FieldLinks.Delete($ColumnInternalName)
#$ContentType.Update()
}
}

Done! Again when trying to delete the site column, received "This site column will be removed and all list columns which were created from it will be permanently orphaned. Are you sure want to delete this site column?"


Well, What does it means? Site columns are created to minimize duplicates and to provide consistency. So, if we delete a site column, all list/library columns created will continue to hold their values. There will not be any impact on the data. But they'll become local columns. Alright, Before deleting a site column lets see where it s actually being used? Lets Find all references of our Site Column in a particular site collection using PowerShell.

PowerShell script to Find a Site column usage on Lists
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site URL
$SiteURL = "http://sharepoint.crescent.com/sites/operations"
#Column to search
$ColumnInternalName = "BranchLocation"

#Get the Web
$Site = Get-SPSite $SiteURL
#Get the Column
$column = $site.RootWeb.Fields.GetFieldByInternalName($ColumnInternalName)

#Find all List usages of the column
$SiteColumnUsages = $column.ListsFieldUsedIn() #Gets the WebID & ListID values

#Get the lists where the site column is being used
foreach( $Usage in $SiteColumnUsages )
{
$Site.AllWebs | foreach {$_.Lists} | where {$_.ID –eq $Usage.ListID } | Select Title, ParentWebURL, RootFolder
}

Write-Host "Checking Lists to Remove the Site column..."
foreach( $Usage in $SiteColumnUsages )
{
#Remove columns from Lists where its used
$List = $Site.AllWebs | foreach {$_.Lists} | where {$_.ID –eq $Usage.ListID }
if($List.Fields.ContainsFieldWithStaticName($ColumnInternalName))
{
$field = $List.Fields.GetFieldByInternalName($ColumnInternalName)

## Uncomment these four lines to actually delete a site column from Lists
#$field.AllowDeletion = $true
#$field.Update()
#$List.Fields.GetFieldByInternalName($ColumnInternalName).Delete()
#$List.Update()
Write-Host "Site column $($ColumnInternalName) has been removed from $($List.RootFolder) at $($List.ParentWeb.URL)"
}
}

How to Upload a List Template using PowerShell

$
0
0
Task: Upload a custom list template to specific site collections in a web application. While upload a list template using from SharePoint web interface is simple, wanted to automate this process as its repeating for multiple site collections.

So, Here is the PowerShell script to upload custom list template to SharePoint site :
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

Function UploadListTemplate($WebURL, $TemplateFilePath)
{
#Get the Web
$web = Get-SPWeb $WebURL
#Get the List template Gallery Folder
$TemplateFolder = $web.GetFolder("List Template Gallery")
#Get the Files collection
$TemplateFileCollection = $TemplateFolder.Files
#Get the Template file from Local File system
$TemplateFile = Get-ChildItem $TemplateFilePath

#Open the File in Read mode and Add to Templates collection
$TemplateFileCollection.Add("_catalogs/lt/$($TemplateFile.Name)", $TemplateFile.OpenRead(), $true)
Write-Host "Done!Template has been uploaded!!"
}

#Call the function
UploadListTemplate "http://sharepoint.crescent.com" "D:\Templates\CustomTaskList.stp"

Increase Maximum size of Site, List Templates in SharePoint

$
0
0
In SharePoint 2007, You can't save a list or site template (.stp ) file which is bigger than 10MB. MOSS 2007 gives an error message:
" The list is too large to save as a template. The size of a template cannot exceed 10485760 bytes."
When you try to save a list or site which by including its content which is more than 10 MB.

Fix is simple: Just execute this stsadm command line from your SharePoint WFE server. Say, you want to allow site or list template up to 250 MB:
stsadm -o setproperty -propertyname max-template-document-size -propertyvalue 262144000  (250 MB)

The above STSADM sets the property at farm level. Here the command line takes property value in bytes.

SharePoint 2010 list template size limit:
In SharePoint 2010 and in SharePoint 2013, list template size limit has been raised to 50MB by default.
sharepoint list template maximum size
If you have a document library or list or site with content more than 50MB and when you try to save list as a template including content, by going to list settings >>"Save document library as template", you get this error message:
sharepoint 2010 list template maximum size
SharePoint 2013 version's Error message:
sharepoint 2013 site template maximum size


Same old stsadm can help to increase the template size limit in both SharePoint 2010 and 2013:

Using PowerShell to Get/Set SharePoint list template maximum size:
Its also possible to use PowerShell. Here is an example of setting SharePoint 2010 list / site template maximum size:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#For MOSS 2007, Uncomment below two lines
#[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
#[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")

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

#Get the current Maximum Size
$webservice.MaxTemplateDocumentSize

#Set New Limit and update
$webservice.MaxTemplateDocumentSize = 524288000 #500 MB
$webservice.Update()
Although the maximum template size in SharePoint 2010 or in SharePoint 2013 can be set to: 524288000 (500 MB), Always try to keep it in lower than: 50 MB

How to Get Managed Account Password in SharePoint?

$
0
0
SharePoint Managed accounts feature was introduced in its 2010 version, and of course its a wonderful feature to manage service accounts (I remember those old days.. We used to create a batch file to update password for each and everything in SharePoint 2007!). So, We utilized managed accounts in SharePoint 2013, enabled automatic password change. All went well until we needed the password for a particular managed account to install a third-party add-on! Luckily found this script to get managed account passwords in SharePoint.
Important: You must run this script as Farm Administrator!

Here is the PowerShell script to retrieve SharePoint managed account passwords:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

function Bindings()
{
return [System.Reflection.BindingFlags]::CreateInstance -bor
[System.Reflection.BindingFlags]::GetField -bor
[System.Reflection.BindingFlags]::Instance -bor
[System.Reflection.BindingFlags]::NonPublic
}
function GetFieldValue([object]$o, [string]$fieldName)
{
$bindings = Bindings
return $o.GetType().GetField($fieldName, $bindings).GetValue($o);
}
function ConvertTo-UnsecureString([System.Security.SecureString]$string)
{
$intptr = [System.IntPtr]::Zero
$unmanagedString = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($string)
$unsecureString = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($unmanagedString)
[System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($unmanagedString)
return $unsecureString
}

Get-SPManagedAccount | select UserName, @{Name="Password"; Expression={ConvertTo-UnsecureString (GetFieldValue $_ "m_Password").SecureStringValue}}

This script decrypts and retrieves all SharePoint 2010 / SharePoint 2013 managed account passwords along with its user names.

Related post: How to Get IIS Application Pool Password?

Update List Item Metadata Fields (Created By, Last Modified) using PowerShell

$
0
0
Ever wanted to update SharePoint list or library item's metadata fields such as: "Created By" "Modified By" "Created" "Last Modified"? These column values must be updated while copying items from one list to another, programmatically.

Today, Had an another requirement to update metadata fields in a document stored in SharePoint document library. Lets update these metadata fields such as "Created By" "Modified By" "Created" "Last Modified" using PowerShell.

PowerShell Script to Update Metadata Fields in SharePoint:

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#Define the Parameters
$WebURL = "http://sharepoint.crescent.com/projects/1033/"
$LibraryName = "Project Documents"
$DocumentName = "Project Schedules.xlsx"
$UserName = "Global\EricCo"
$DateValue = "2013-01-01 10:05" # Should be in "yyyy-mm-dd HH:mm" format

#Get the Web
$web= Get-SPWeb $WebURL
#Get the Library
$list= $web.Lists[$LibraryName]
#Get the User
$Author =$web.EnsureUser($UserName)
#Get the document
$Document = $list.Items | where {$_.Name -eq $DocumentName}

#update created by column sharepoint programmatically
$Document["Author"] = $Author
#set modified by programmatically
$Document["Editor"] = $Author

#Set Created Date value
$Document["Created"] = $DateValue
#Set Last Modified Date
$Document["Modified"] = $DateValue

$Document.UpdateOverwriteVersion() #Can use $Document.SystemUpdate() as well..

Find All Users who Accessed the SharePoint Sites in the Past One Year

$
0
0
Requirement: Get the E-mail ids of all users who accessed SharePoint sites during the past one year!

Solution: Lets use Log Parser and PowerShell to fulfill this requirement. Here is how:
  1. Locate your SharePoint web application's log folders from all web front servers (usually: C:\WINDOWS\system32\LogFiles\W3SVCxxxxxxxxx\") using IIS. Make a note of them.
  2. Execute this log parser query by substituting LOG folders path, from any one of the Web Front end
  3. Use the data we received from log parser, pass it to PowerShell to query e-mails from active directory.
Log parser query to get all users:
@path=C:\Program Files\Log Parser 2.2\

LogParser -i:W3C "SELECT TO_LOWERCASE(cs-username) As UserName, count(*) as [Total Hits] INTO PortalUsersFeb.csv FROM E:\MOSS2007\LogFiles\W3SVC1297965057\*, \\MOSS07-WFE02\E$\MOSS2007\LogFiles\W3SVC1297965057\*, \\MOSS07-WFE03\E$\MOSS2007\LogFiles\W3SVC1297965057\* WHERE date > '2013-03-01' AND cs-username Is Not Null group by TO_LOWERCASE(cs-username)" -o:CSV

pause
Place the above code in a batch file(.bat) and execute from any SharePoint web front end. This should give a CSV file with list of users. Alright, we got the list of user names. And now, we needed their E-mail IDs. Lets query active directory to get the E-mail ids of the users.

Query AD to Get user E-mail from user ID:
#Function to Check if an User exists in AD
function Get-Email()
{
Param( [Parameter(Mandatory=$true)] [string]$UserLoginID )

#Search the User in AD
$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
#To Search on other forests use these three lines:
#$ForestName ="corporate.crescent.org"
#$adCtx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("forest", $ForestName)
#$forest = ([System.DirectoryServices.ActiveDirectory.Forest]::GetForest($adCtx))

#Search in all domains
foreach ($Domain in $forest.Domains)
{
$context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $Domain.Name)
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)

$root = $domain.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = "(&(objectCategory=User)(samAccountName=$UserLoginID))"
$result = $search.FindOne()

#If user found
if ($result -ne $null)
{
$result.Properties["mail"]
}
}
}

##Read the CSV file - Map the Columns to Named Header
$CSVData = Import-CSV -path "E:\Users.csv" -Header("UserAccount")
#Iterate through each Row in the CSV
foreach ($row in $CSVData)
{
$mail = Get-Email $row.UserAccount
$row.UserAccount +","+ $mail >>"E:\data\Mails.csv"
}
This script outputs a CSV file by searching AD. Please note, the $UserLoginID parameter is simply user's login name without domain. (E.g. if Global\Salaudeen is the user name, we'll have to pass only "Salaudeen" to Get-Email function).

How to Disable "I Like It" "Tags & Notes" in SharePoint 2010

$
0
0
'I Like it' and 'Tags and Notes' features are introduced in SharePoint 2010 to improve user collaboration, social communication capabilities and to enable users to provide their feedback on items, pages, etc. However, not all SharePoint environments requires this feature, so here are some ways to to remove "I like it" and "Tags & Notes" tag buttons from SharePoint 2010.
Removing "I Like It" and "Tag and Notes" from SharePoint Site
 
SharePoint 2010 disable "I Like It" "Tags and notes" at farm level:
If you want to remove "I like It" , "Tags & Notes" at farm level, follow these steps:
  • Go to Central Administration >> System Settings >> Click on "Manage Farm Features"  How to Remove the “I like it” and “Tag & Notes”
  • Deactivate "Social Tags and Note board Ribbon Controls"Hiding the social tags in SharePoint 2010
Or you can disable by PowerShell
Disable-SPFeature –Identity SocialRibbonControl

To enable, use:
Enable-SPFeature –Identity SocialRibbonControl
Microsoft KB to turn off the "I Like It" and the "Tags & Notes" features in SharePoint Server 2010: http://support.microsoft.com/kb/983263/en-US

While this change is instant and disables/enables social tags at farm level for all web applications, We can target this setting based on user group too. Here is how:

Disable social tagging permissions to specific users and groups:
You can also enable/disable social tagging feature for specific users or groups by removing them from the Use Social Features permission, which is part of the User Profile service application.
  • Go to Central Admin >> Click on Manage Service Applications
  • Pick your User Profile Service Application from the list
  • Click on "Manage User Permissions" link under People section
  • Select the user or group for which you want to turn off the "I Like It" and the "Tags & Notes" features.
  • Under Permissions, click to clear the Use Social Features check box. and click OK.SharePoint 2010: Disable "I like it" und "Tags and Notes"
It takes a minute (by a timer job!) and this setting is a cumulative (you remove permission from one group and you grant for one! Then the user will be able to see )
How to remove "I like it" and "Tags & Notes" from SharePoint 2010

You can also use my solution How to Hide SharePoint 2010 Ribbon Tab - Group - Button - Menu to disable/hide/remove "I Like It" tags on particular site/site collection. It actually uses the "CustomAction" feature to hide those buttons.

Hide I Like It Tags & Notes using CSS:
Use IE developer toolbar or Firebug in Firefox to get the ID/Class of the tags, and set its visibility to none.
sharepoint 2010 i like it feature removePlace this css code in your SharePoint 2010 Master page, or custom style sheet, wherever applicable.
/* SharePoint 2010 hide i like it tags & notes CSS code */
<style type="text/css">
.s4-socialdata-notif
{
display:none;
}
</style> 

SharePoint 2010 remove i like it cCSS
Unlike the above requirement, you may have to disable i like it button alone with CSS. Here is the  code: 
/* sharepoint 2010 hide i like it css */
<style type="text/css">

#AddQuickTag_ctl00_ctl36 {
display:none;
}
#AddQuickTagImg_ctl00_ctl36 {
display:none;
}
</style>
SharePoint 2010 i like it disabled 
How about securing it : with SharePoint Security Trimmed Control? 
Edit your master page, Find:
<SharePoint:DelegateControl ControlId="GlobalSiteLink3" Scope="Farm" runat="server"/>
and move it inside:
<Sharepoint:SPSecurityTrimmedControl runat="server" Permissions="ManagePermissions">

<SharePoint:DelegateControl ControlId="GlobalSiteLink3" Scope="Farm" runat="server"/>

</SharePoint:SPSecurityTrimmedControl>
You can even set style="display:none" for the above element in Master page to make it hidden. For all available permission strings, refer: http://msdn.microsoft.com/EN-US/library/ms412690

SharePoint 2010 i like it feature disabled?
"I Like It" not available in SharePoint 2010? those button missing? Here is how to enable "I Like it":
Check all of the above discussed things in reverse order! Additionally, Its depending on "User Profile " and "Managed Metadata Service Application", So make sure these SAs are up and running and associated via "Service connection" with the web application. You may get "Notes & Tags" alone, if you have only user profile service application configured and associated. (If you don't have UPSA, you won't see neither of them!)

Add/Remove/Get Event Receivers in SharePoint with PowerShell

$
0
0
We usually use C# console application or feature activation code to register event receivers with the target list or library in SharePoint. At times, we may have to handle event receiver associations explicitly. Of course, there are some great tools in codeplex (E.g. http://speventreceiverman.codeplex.com/) to manage event receivers. However, in a production environment, which didn't allow me to use any such tools for security reasons, I'm left with the option: PowerShell. Hence, I'm sharing my PowerShell code snippets to manage event receivers in SharePoint using PowerShell.

Get all event receivers attached with a List:
Lets find in SharePoint 2010 PowerShell to get event receivers associated with a particular list.
 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the web
$Web = Get-SPWeb "http://sharepoint.crescent.com"

#Get the Target List
$List = $Web.Lists["Documents"]

#Retrieve all event receivers associated with the list
$List.EventReceivers | Select Id, Type, Assembly, Class | FL
Lets find all Event receivers on all sites in a web application:
Similarly, We can retrieve all event receivers associated with various lists and libraries across all site collection using the below PowerShell script.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebAppURL = "http://sharepoint.crescent.com"

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

foreach($web in $Webs)
{
#Get Lists with Event receivers excluding System lists
$web.lists | where { ($_.Author.LoginName -ne "SHAREPOINT\system") -and ($_.Hidden -eq $false) -and ($_.IsCatalog -eq $false) -and ($_.IsSiteAssetsLibrary -eq $false) -and ($_.EventReceivers.count -gt 0) } | Select Title, EventReceivers | FL
}

SharePoint 2010 powershell add event receiver
Usually, we create a C#.net console application to associate a event receiver to a particular list. This time, I tried with PowerShell script:

Lets add event receiver by creating the definition in PowerShell:
#Get the web
$Web = Get-SPWeb "http://sharepoint.crescent.com"

#Get the Target List
$List = $Web.Lists["Documents"]

#Add new event receiver definition
$def = $list.EventReceivers.Add()
$def.Assembly = "Crescent.DocRestrict, Version=1.0.0.0, Culture=neutral, PublicKeyToken=677b45b1314c252c"
$def.Class = "Crescent.Utilities.DocRestrict.Restrict"
$def.Type = [Microsoft.SharePoint.SPEventReceiverType]::ItemAdded
$def.Name = "ItemAdded Event Receiver";
$def.SequenceNumber = 3000
$def.Synchronization = [Microsoft.SharePoint.SPEventReceiverSynchronization]::Synchronous
$def.Update()

Alternatively, in SharePoint 2010 to add event receiver to list with PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the web
$Web = Get-SPWeb "http://sharepoint.crescent.com"

#Get the Target List
$List = $Web.Lists["Documents"]

#Retrieve all event receivers associated with the list
#$List.EventReceivers | Select Id, Type, Assembly, Class | FL

$Assembly = "Crescent.DocRestrict, Version=1.0.0.0, Culture=neutral, PublicKeyToken=677b45b1314c252c"
$Class= "Crescent.Utilities.DocRestrict.Restrict"
Write-Host "Attaching Event Receiver..."
# sharepoint 2010 powershell register event receiver
$list.EventReceivers.Add("ItemAdding", $Assembly , $Class)

How about content types? can add event receiver using PowerShell? why not?
#Get the content type
$ctype = $web.ContentTypes["content type name"]
#Add event receiver
$ctype.EventReceivers.Add("ItemAdding", "Assembly Name", "Class")

Remove Event Receiver:
To delete event receiver using PowerShell in SharePoint, here is the code:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the web
$Web = Get-SPWeb "http://sharepoint.crescent.com"

#Get the Target List
$List = $Web.Lists["Documents"]

$Assembly = "Crescent.DocRestrict, Version=1.0.0.0, Culture=neutral, PublicKeyToken=677b45b1314c252c"

$EventReceivers = $list.EventReceivers | Where {$_.Assembly -eq $assembly}

if ($EventReceivers) #.Count -gt 0)
{
foreach($Receiver in $EventReceivers)
{
Write-Host "Deleting Event Receiver from " $list.RootFolder.ServerRelativeUrl

$Receiver.Delete()
}
}
SharePoint PowerShell remove event receiver:
You can also delete a particular event receiver by its ID.
 #Get the web
$Web = Get-SPWeb "http://sharepoint.crescent.com"

#Get the Target List
$List = $Web.Lists["Documents"]

#Get all event receivers associated with the list
$List.EventReceivers | Select Id, Type, Assembly, Class | FL

#$EventReceiverID = "625c59a9-72d7-4479-a1e7-35f040e4f9a1"
#Uncomment below line to sharepoint 2010 remove event receiver from list powershell
#$list.EventReceivers[[GUID]$EventReceiverID].delete()

Remove Duplicate Event Receivers:
Duplicate instances of SharePoint event receivers is a known issue. They share a common assembly with different sequence numbers. So they fire twice.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the web
$Web = Get-SPWeb "http://sharepoint.crescent.com"

#Get the Target List
$List = $Web.Lists["Documents"]

#Get all event receivers grouped by assembly/class/type
$list.EventReceivers | Group-object assembly, class, type | where { $_.Count -gt 1 }

#If any of assembly/class/type pairs are same, we have a duplicate!

#Leave the first event receiver at 0th position and delete all other
$list.EventReceivers | Group-object assembly, class, type | where { $_.Count -gt 1 } | foreach { $_.Group[1..50] } | foreach { $_.Delete() }
To Add event receivers with SharePoint list Programmatically, refer: sharepoint powershell add event receiver to list

SharePoint Web Part Usage Report - Find All Locations where a Particular web part is being Used

$
0
0

During Migration, I had to get the URLs where a particular web part is being used. So, Used this PowerShell script to generate SharePoint web part usage report.

This script made compatible with SharePoint 2007, So it can be used in SharePoint 2010 and in SharePoint 2013 as well. Just change the Web Application URL from "http://sharepoint.crescent.com" to yours.

SharePoint Web Part Usage Report using PowerShell:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

Function global:Get-SPWebApplication($WebAppURL)
{
return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
}

#Get-SPSite cmdlet for MOSS 2007
function global:Get-SPSite($url)
{
return new-Object Microsoft.SharePoint.SPSite($url)
}

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

#Write Header to CSV File
"Page URL, Web Part Name" | out-file "D:\Data\ExcelServicesWPs.csv"

#Get all Webs
$WebApp = Get-SPWebApplication "http://sharepoint.crescent.com"
foreach($site in $WebApp.Sites)
{
#Iterate through webs
foreach ($web in $site.AllWebs)
{
#Get All Pages from site's Root into $AllPages Array
$AllPages = @($web.Files | Where-Object {$_.Name -match ".aspx"})

#Search All Folders for Pages
foreach ($folder in $web.Folders)
{
#Add the pages to $AllPages Array
$AllPages += @($folder.Files | Where-Object {$_.Name -match ".aspx"})
}

#Iterate through all pages
foreach($Page in $AllPages)
{
$webPartManager = $web.GetLimitedWebPartManager($Page.ServerRelativeUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

# Array to Hold Closed Web Parts
foreach ($webPart in $webPartManager.WebParts | Where-Object {$_ -like "*Excel*"})
{
$result = "$($web.site.Url)$($Page.ServerRelativeUrl), $($webpart.Title)"
Write-Host "Web Part Found at: "$result
$result | Out-File "D:\Data\ExcelServicesWPs.csv" -Append
}
}
}
}
This script scans all libraries (not just "Site Pages" or "Pages" library! What if a web part page stored in a "documents" library?) from all sites where a particular webpart is being used and generates report in CSV format.

Find Who has Created / Modified a SharePoint View

$
0
0
Every wondered how to find the user who has created/modified a particular SharePoint view? and when it was created/modified? Well, There is no SharePoint UI to get these information! But using SharePoint object model, we can retrieve these data programmatically from SPFile object's properties.

Here is how I retrieved "Created By", "Created On", "Modified By", "Modified On" values using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set these two variables accordingly
$WebURL = "http://sharepoint.crescent.com/"
$ViewURL = "http://sharepoint.crescent.com/LegalDoc/AuthorView.aspx"

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

#Get the View File
$ViewFile = $web.GetFile($viewURL)

Write-Host "Created By: " $ViewFile.Author
Write-Host "Created on: " $ViewFile.TimeCreated
Write-Host "Modified By: " $ViewFile.ModifiedBy
Write-Host "Modified On: " $ViewFile.TimeLastModified

Exclude a Column from SharePoint Search Crawl

$
0
0
Requirement:
We keep few fields for configuration in a custom SharePoint application and don't want those fields to appear in SharePoint Search results.

Solution:
SharePoint Fields/Columns has a property: NoCrawl, just turn it ON, we can exclude columns from SharePoint Search! Here is how I turned Off search visibility of a field using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set these two variables accordingly
$WebURL = "http://sharepoint.crescent.com"
$FieldName = "ConfigData"

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

#Get the field
$Field = $web.Fields[$FieldName]

#Set the search prefererence
$Field.NoCrawl = $true
$Field.Update($true)
It takes effect after a search crawl takes place.

Import XML File Data into SharePoint List using PowerShell

$
0
0
Requirement: We've an utility from third-party system that generates project data in XML format. We had to import those data to a list in the PMO site. In other words: We've to import from XML file to SharePoint list.

Here is a sample XML file, generated by the tool:
<?xml version="1.0"?>
<projects>
<project id="PMO.1120">
<description>GIS upgrade 2013 </description>
<manager>global\E372440</manager>
<cost>$35000</cost>
<startdate>1/1/2014</startdate>
</project>
<project id="PMO.1121">
<description>HRIT Asset Life Cycle Automation</description>
<manager>AMER\E132321</manager>
<cost>$63000</cost>
<startdate>1/1/2014</startdate>
</project>
</projects>

Solution: Using PowerShell, lets import XML data into SharePoint list.

PowerShell script to read from XML and import to SharePoint list:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set these two variables accordingly
$WebURL = "http://project.crescent.com/"
$ListName = "External Projects"
$XMLFilePath = "D:\data\ExternalProjects.xml"

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

#import xml file
[xml]$ProjectXmlFile = Get-Content $XMLFilePath

foreach ($XMLProject in $ProjectXmlFile.projects.project)
{
$NewProject = $ProjectList.Items.Add()

$NewProject["Project ID"] = $XMLProject.id
$NewProject["Description"] = $XMLProject.description
#Set the People Picker Field
$NewProject["Project Manager"] = $web.EnsureUser($XMLProject.manager)
$NewProject["Cost"] = $XMLProject.cost
$NewProject["Start Date"] = $XMLProject.startdate

$NewProject.Update()
Write-Host "Project $($XMLProject.id) has been Added to External Projects list!"
}
That's all! we are done importing XML data to sharepoint list with PowerShell!!

Export SharePoint List Items to XML using PowerShell

$
0
0
Sometime back, I wrote a PowerShell script to import from a XML file to SharePoint list  Import XML File Data into SharePoint List using PowerShell. Now the requirement is in reverse: Export SharePoint List data to XML file!

PowerShell script to Export SharePoint List Items to XML:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set these three variables accordingly
$WebURL = "http://projects.crescent.com/"
$ListName = "External Projects"
$XMLFilePath = "E:\data\ExternalProjects.xml"

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

#Create a XML File
$XMLFile = New-Object System.Xml.XmlDocument
#Add XML Declaration
[System.Xml.XmlDeclaration] $xmlDeclaration = $XMLFile.CreateXmlDeclaration("1.0", "UTF-16", $null);
$XMLFile.AppendChild($xmlDeclaration) | Out-Null

#Create Root Elemment "Projects"
$ProjectsElement = $XMLFile.CreateElement("Projects")

#Iterate through each list item and send Rows to XML file
foreach ($Item in $ProjectList.Items)
{
#Add "Project" node under "Projects" Root node
$ProjectElement = $XMLFile.CreateElement("Project")
#Add "ID" attribute to "Project" element
$ProjectElement.SetAttribute("id", $Item["ID"])
$ProjectsElement.AppendChild($ProjectElement) | Out-Null

#Populate Each Columns
#Add "Description" node under "Project" node
$DescriptionElement = $XMLFile.CreateElement("description");
$DescriptionElement.InnerText = $Item["Description"]
#Append it to "Project" node
$ProjectElement.AppendChild($DescriptionElement) | Out-Null

#Add "Project Manager" element under "Project" node
$managerElement = $XMLFile.CreateElement("manager");
$managerElement.InnerText = $Item["Project Manager"]
#Append it to "Project" node
$ProjectElement.AppendChild($managerElement) | Out-Null

#Add "Cost" element under "Project" node
$CostElement = $XMLFile.CreateElement("cost");
$CostElement.InnerText = $Item["Cost"]
#Append it to "Project" node
$ProjectElement.AppendChild($CostElement) | Out-Null
}
#Close the Root Element
$XMLFile.AppendChild($ProjectsElement) | Out-Null
#Save all changes
$XMLFile.Save($XMLFilePath)
XML file generated:
export sharepoint list to xml powershell
Another nifty trick would be: Export SharePoint list to Ms-Access, and then from there, export tables to XML!
export sharepoint 2010 list to xml file
You can also export/view SharePoint List items to XML format using RPC call, refer: Retrieve SharePoint List data in XML format

Add Custom Scope to SharePoint Search Dropdown using PowerShell

$
0
0
Requirement: We've created a custom search scope "Search All Documents" in SharePoint Central Admin and would like to include it in search scope drop downs of few site collections.

SharePoint 2010 add search scope to drop down:
Well, its a few-clicks job to include custom search scopes to search drop down in SharePoint. Here is how:
  1. Go to Site Actions >> Site Settings
  2. Click on "Search Scopes" link under Site collection administration
  3. Click on "Display Groups" link and choose "Search Dropdown"
    Edit Search Dropdown Scopes
  4. From here, we can include/exclude any scopes to search dropdown by simply selecting/deselecting check-boxes.Edit Search Scopes Dropdown
Add custom scope to SharePoint Search Scope Drop downs using PowerShell
While its not tedious to customize search scope dropdowns by following above steps for few site, We had to do it for all site collections under a particular managed path.(around 50!). Here is the PowerShell script to add custom search scopes to SharePoint search dropdown:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set these three variables accordingly
$SiteURL = "http://sharepoint.crescent.com/sites/operations/"
$CustomSearchScopeName = "Search All Documents"
$DisplayGroupName = "Search Dropdown"

#Get the Site Object
$Site= Get-SPSite $siteURL

#Initialize
$SearchContext= [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($site)
$Scopes= New-Object Microsoft.Office.Server.Search.Administration.Scopes($searchContext)

#Get the Display Group
$SearchDropdownDisplayGroup = $scopes.GetDisplayGroupsForSite($SiteURL) | Select-Object -First 1
#Get the custom scope
$CustomSearchScope = $Scopes.GetSharedScope($CustomSearchScopeName)

#Add custom scope to Display group
$SearchDropdownDisplayGroup.Add($CustomSearchScope)
$SearchDropdownDisplayGroup.Update()
See the result in action:Include Custom Scope to SharePoint Search Dropdown PowerShell

SharePoint 2010 Search Scope Drop Down Missing?

$
0
0
SharePoint 2010 search drop downs such as "All Sites", "People" missing in site collections? Shows only "Search This site..." in search box? Well, That's the default setup in SharePoint 2010.
sharepoint 2010 search scope drop down missing
Enable SharePoint 2010 add search scope drop down:
How to enable search scope drop down in SharePoint 2010? simple, follow these steps:
Make sure you have a Search Center site created already, before proceeding to these steps.
  1. Go to Site Actions >> Site Settings 
  2. Click on "Search Settings" link under Site Collection Administration group. sharepoint 2010 search scope drop down missing
  3. Under "Site Collection Search Center" section, Choose "Enable Search Scopes" and enter the URL of your search center.
  4. On "Site Collection Search Dropdown Mode", choose "Show Search Dropdown"
  5. Click "Ok" to save your changes.

Now the searh box should show you a drop down with "All Sites", "People" Scopes in SharePoint 2010 sites along with "This Site" scope.
sharepoint 2010 search scope drop down

Copy Attachment from SharePoint List to Document Library using SharePoint Designer - PowerShell

$
0
0
SharePoint keeps attachments under "List >> Attachments >> 'List Item ID'" folder path. So, if you want to copy attachment from list to document library, follow these steps:
  1. Open your SharePoint site from SharePoint Designer
  2. Navigate to "All Files" view >> Lists >> Your Source List >> Attachments folder. Here, folders are created based on list item's ID. 
    sharepoint copy attachment from list to document library
  3. Just copy attachment files from these folders and navigate to the target document library and paste there.sharepoint designer 2010 copy attachment
Well, it would be tedious to copy list attachment to document library, if you have large number of list items/attachments. So, lets use PowerShell in SharePoint to copy list attachment to document library.


PowerShell script to copy attachment from list to document library:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebURL = "http://sharepoint.crescent.com/pmo/GIS/"

$SourceListName = "External Projects"
$TargetLibraryName = "Design Documents"

#Get the Web List and Library objects
$web = Get-SPWeb $WebURL
$SourceList = $web.Lists[$SourceListName]
$TargetLibrary = $web.Lists[$TargetLibraryName]

#Loop through each list item
foreach ($ListItem in $SourceList.Items)
{
if($ListItem.Attachments.Count -gt 0)
{
#Loop through each attachment in the list item
foreach ($Attachment in $ListItem.Attachments)
{
#Get the attachment
$file = $web.GetFile($ListItem.Attachments.UrlPrefix+$Attachment)
$bytes = $file.OpenBinary()

$TargetFileName = $TargetLibrary.RootFolder.Url+"/"+$Attachment
$TargetFile = $TargetLibrary.RootFolder.Files.Add($TargetFileName, $bytes, $true)
Write-Host "Copied to: $($TargetFilename)"
}
}
}
This script copies all attachments from all list items to the given library's root folder. You can tweak the script little to create sub-folders in the target library too.

Get SharePoint Site Collection, Web, List Objects from GUID

$
0
0
Requirement: On Nintex workflow databases, Ran a query to fetch workflow usage statistics, and the query gave GUIDs of SPSite, SPWeb and SPList objects!

SELECT TOP 100 
I.WorkflowName,
I.WorkflowInstanceID,
I.SiteID,
I.WebID,
I.ListID,
I.ItemID,
I.WorkflowInitiator,
I.WorkflowID,
I.State, COUNT(P.WorkflowProgressID) as WorkflowProgressRecords
FROM WorkflowInstance I inner join WorkflowProgress P WITH (NOLOCK)
ON I.InstanceID = P.InstanceID
--WHERE i.State=2
GROUP BY I.WorkflowName, I.WorkflowInstanceID, I.SiteID, I.WebID, I.ListID, I.ItemID, I.WorkflowInitiator, I.WorkflowID, I.State
ORDER BY COUNT(P.WorkflowProgressID) DESC
Get SharePoint Site Collection, Web, List Objects from GUID
Well, from SQL query we got GUIDs of SharePoint site collection, web and list objects, but how do we get the actual site collection/site/list locations? PowerShell comes to rescue. Here is the PowerShell script to get SharePoint site collection, web, list objects from GUID.
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")  

#Get-SPWeb cmdlet for MOSS 2007
Function global:Get-SPWeb($SiteGUID, $WebGUID)
{
$site = New-Object Microsoft.SharePoint.SPSite($SiteGUID)
if($site -ne $null)
{
$web=$site.OpenWeb($WebGUID);
}
return $web
}
#GUIDs for Site, Web and List
$SiteGUID = [GUID]("294D0050-19BE-439E-BF87-246F07828DAE")
$WebGUID = [GUID]("AEDA6502-83C5-4967-A4C6-DF26B6F1ABDA")
$ListGUID =[GUID]("1A54DCCD-251A-4B05-A7EC-BF10877C8B90")

#Get the Web
$web = Get-SPweb $SiteGUID $WebGUID
#Get the List
$list = $web.Lists[$ListGUID]

#Get the List title
$list.title
$ListURL = $Web.URL+"/"+$list.RootFolder.URL
write-host $ListURL

Restart SharePoint Timer Service Remotely using PowerShell

$
0
0
SharePoint Timer service must be restarted for certain configuration changes in SharePoint administration activities. Well, without logging into each and every SharePoint server and restarting timer service, we can utilize PowerShell to do it remotely!

PowerShell Script to Restart SharePoint Timer Service Remotely:
 #Service to Restart
$ServiceName = "SPTimerV4"

#Array to Hold server Names. Update this Array accordingly
$ServerNames = @("SPServer01", "SPServer02", "SPServer03")

#Get All SharePoint Servers and restart their SharePoint Timer service
foreach($Server in $ServerNames)
{
Restart-Service -InputObject $(Get-Service -Computer $Server -Name $ServiceName)
}

You can also use the classic WMI method to restart any service on remove server:

#Server Name
$ServerName = "SPServer01"

#Service to Restart
$ServiceName = "SPTimerV4"

#Get Timer Service
$Service = Get-WmiObject -computer $ServerName Win32_Service -Filter "Name='$ServiceName'"
$Service.InvokeMethod('StopService',$Null)
start-sleep -s 5
$Service.InvokeMethod('StartService',$Null)
start-sleep -s 5
Viewing all 1058 articles
Browse latest View live


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