Wednesday, July 31, 2013

Recover SharePoint 2007 / 2010 / 2013 Product Key using PowerShell

Ever wanted to recover your SharePoint 2007 or SharePoint 2010 Product key from an existing SharePoint Farm? Sure! Its encoded and stored in system registry and we can recover the license key with PowerShell. Here is the code:

Here is the PowerShell Script to Recover SharePoint 2007 Product key:
function Get-SP2007ProductKey {    
    $map="BCDFGHJKMPQRTVWXY2346789" 
    $value = (get-itemproperty "HKLM:\SOFTWARE\Microsoft\Office\12.0\Registration\{90120000-110D-0000-1000-0000000FF1CE}").digitalproductid[0x34..0x42]  
    $ProductKey = ""  
    for ($i = 24; $i -ge 0; $i--) { 
      $r = 0 
      for ($j = 14; $j -ge 0; $j--) { 
        $r = ($r * 256) -bxor $value[$j] 
        $value[$j] = [math]::Floor([double]($r/24)) 
        $r = $r % 24 
      } 
      $ProductKey = $map[$r] + $ProductKey 
      if (($i % 5) -eq 0 -and $i -ne 0) { 
        $ProductKey = "-" + $ProductKey 
      } 
    } 
    $ProductKey
} 

#Call the function
Get-SP2007ProductKey 

PowerShell Script to Recover SharePoint 2010 Product Key:
function Get-SP2010ProductKey {    
    $map="BCDFGHJKMPQRTVWXY2346789" 
    $value = (get-itemproperty "HKLM:\SOFTWARE\Microsoft\Office\14.0\Registration\{90140000-110D-0000-1000-0000000FF1CE}").digitalproductid[0x34..0x42]  
    $ProductKey = ""  
    for ($i = 24; $i -ge 0; $i--) { 
      $r = 0 
      for ($j = 14; $j -ge 0; $j--) { 
        $r = ($r * 256) -bxor $value[$j] 
        $value[$j] = [math]::Floor([double]($r/24)) 
        $r = $r % 24 
      } 
      $ProductKey = $map[$r] + $ProductKey 
      if (($i % 5) -eq 0 -and $i -ne 0) { 
        $ProductKey = "-" + $ProductKey 
      } 
    } 
    $ProductKey
} 
#Call the function
Get-SP2010ProductKey

Retrieve SharePoint 2013 Product Key:
For SharePoint 2013, Set the $value parameter in the above code to :
$value = (get-itemproperty "HKLM:\SOFTWARE\Microsoft\Office\15.0\Registration\{90150000-110D-0000-1000-0000000FF1CE}").digitalproductid[0x34..0x42]    
and run the script!

Thanks to http://powershell.com/cs/blogs/tips/archive/2012/04/30/getting-windows-product-key.aspx for the idea!

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


Tuesday, July 30, 2013

Update All Items in a SharePoint List using PowerShell

Use these PowerShell scripts to update all items in SharePoint lists:

SharePoint PowerShell script to update all items in list:
Requirement is to update all items in a SharePoint list using PowerShell script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

### Variables ###
#Site URL and List names
$SiteURL = "http://intranet.crescent.com/"
$ListName = "Business Contacts"                 

#Get site and List objects
$web = Get-SPWeb $SiteURL
$List = $web.Lists.TryGetList($ListName)

if($List -ne $null)
    {    
        #Get all List items
        $ListItems = $list.Items
        
        #Iterate through each item
        Foreach($item in $ListItems)
        {
            #To update a particular field, 
            $item[$FieldName]= NewValue;

            #sharepoint powershell update all items in list
            $item.update()
        }
    }
#dispose web object
$web.Dispose() 

Filter and Update all documents in a SharePoint Library:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

### Variables ###
#Site URL and List names
$SiteURL = "http://intranet.crescent.com/Sites/Sales"
$ListName = "Sales Proposals" 
#Column to update
$FieldName ="Sales Category"
#Field old and new values
$OldValue = "Software"
$NewValue="Applications"

#Get site and List objects
$web = Get-SPWeb $SiteURL
$List = $web.Lists.TryGetList($ListName)

if($List -ne $null)
    {
        #Get all documents with .docx extension
        $DocsCollection = $List.Items | where {$_.Name -match ".docx"}
        
        #Iterate through each document
        foreach ($Doc in $DocsCollection)
        {
            #Change Category Metadata
            if($Doc[$FieldName] -eq $OldValue)
            {
                $Doc[$FieldName] = $NewValue

                #Perform a system update to keep versions, Modified by metadata intact
                $Doc.SystemUpdate($false)
                write-host "Updated an item at: $($doc.URL)"
            }
        }
    }

#dispose web object
$web.Dispose() 
This PowerShell script selectively updates all document's metadata, residing in a library - Including the one inside folders.

Here is an another trick to trigger update on multiple documents in SharePoint:
  • Navigate to your document library
  • Select required documents >> Click on "Check Out" button from ribbon
  • Click on "Check-in"
Update All Items in a SharePoint 2013


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


Thursday, July 25, 2013

How to Rename SharePoint Web Application Name and URL

We may want to change a web application name to make a consistency in naming conventions or in some other scenarios. But I don't find any SharePoint Central Administration options to rename a web application! So how to rename SharePoint 2010 web application Name? well, PowerShell can help!

Rename SharePoint web application name using PowerShell: 
PowerShell can be used to rename web application name in SharePoint 2010. Lets rename SharePoint web application using PowerShell 

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Function to Rename SharePoint Web Application
Function RenameWebApp($OldName, $NewName)
{  
   #Get the Web Application by its Name
   $WebApp =Get-SPWebApplication | where {$_.Name -match $OldName}

   #sharepoint 2010 rename web application powershell
   $WebApp.Name= $NewName

   $WebApp.Update()
   Write-Host "Web Application Name Changed from: $($OldName) to $($NewName)"
}

#Call the function to Rename Web App
RenameWebApp "External Site" "Extranet"

However, this PowerShell script just renames the web application name but not the URL! I don't find a way in SharePoint 2010 to rename web application with PowerShell.

How to Rename SharePoint web application URL
To rename a web application URL in SharePoint, We've to update the DNS entries, Alternate access mapping (AAM) in Central Administration and update the Host header bindings in IIS.

To Rename SharePoint 2010 web application URL, lets update the AAM entries first. Go to: Central Administration >> System Settings >> Configure alternate access mappings under Farm Management. Pick your web application and give a new URL to it.
how to rename sharepoint 2010 web application

Update HOST Name in IIS Bindings to rename SharePoint Web application URL:
Next step is to update IIS bindings. Go to IIS (Start > Run > InetMgr), Select your target web application, Click on "Bindings" on right pane.
how to change web application url in sharepoint

Click on "Edit" and then update the "Host Name" with new URL for the web application.
sharepoint change url of web application
That's all! we are done. The above steps applicable to SharePoint 2007 also to change web app URL.
You can extend an existing SharePoint web application to give a new Name and URL for it!


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


Tuesday, July 16, 2013

SharePoint Workflows Inventory Report using PowerShell

In continuation with my another post: Workflows Inventory Report for SharePoint , which was done using C# object model code, This is a PowerShell version to find all workflows deployed in the SharePoint environment to generate the workflows Inventory report.

Basically, this script iterates through all site collections-sites-List objects to fetch workflow data such as: Workflow Name, Running instances, etc.
#For SharePoint 2007 Compatibility
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

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

#Function to Get the workflow inventory for the entire web application
function Get-WorkflowInventory([string] $WebAppURL)
{
    #Get the Web Application URL
    $WebApp = Get-SPWebApplication $WebAppURL  
 
    #Iterate through each site collection
    foreach ($Site in $WebApp.Sites)
          {                              
                #Loop through each site     
                foreach ($Web in $Site.AllWebs)
                   {
                    #Loop through each list
                    foreach ($List in $Web.Lists)
                      {
                         # Leave hidden Lists and Libraries
                         if($List.Hidden -eq $false)
                         {
                            foreach ($WorkflowAssociation in $List.WorkflowAssociations)
                            {
                                #Leave the "Previous Versions"
                                if($WorkflowAssociation.Name.Contains("Previous Version") -eq $false)
                                    {
                                       $data = @{
                                        "Site" = $Site.Rootweb.Title
                                        "Web" = $Web.Title
                                        "Web URL" = $Web.Url
                                        "List Name" = $List.Title
                                        "List URL" =  $Web.Url+"/"+$List.RootFolder.Url
                                        "Workflow Name" = $WorkflowAssociation.Name
                                        "Running Instances" = $WorkflowAssociation.RunningInstances
                                        }
                                        
                                        #Create a object
                                        New-Object PSObject -Property $data
                                    }
                              }
                          }                    
                    }
                     $Web.Dispose()                  
                }
                $Site.Dispose()                   
    }
} 

#call the function
Get-WorkflowInventory "http://sharepoint.crescent.com" | Export-Csv -NoTypeInformation -Path D:\Reports\WorkflowInventory.csv

write-host "Workflows Inventory report has been generated successfully!"

Tail: How to find all SharePoint designer workflows?
While the above workflow gives workflow data on all workflows, its possible to find only SharePoint designer made workflows by checking the below condition:
if( ($WorkflowAssociation -eq $null) -and ($WorkflowAssociation.InternalName.Contains("Xoml")))
              {
                  #This is a SharePoint Designer Workflow
              }


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


Monday, July 15, 2013

Hide SharePoint List Columns based on User Permissions

Requirement: We've a "Requests" link in our Help Desk site. The "Status" field in help desk requests list should be hidden when users create new entry in the list. Same time, Status field must be visible to people in "Help desk operators" group.

So, the requirement is to hide SharePoint List Form field based on user permissions!

Solution: Use SPServices to check whether the current user is member of a particular group. If not,  hide the field using jQuery (or you can make the field Read-only too: How to Make SharePoint List Column Read Only ). Here is the detailed steps:
  1. Place the below script in a text file, upload to any SharePoint library of the site.
  2. Edit the NewForm.aspx, Add a content editor web part just below form fields, point the script file in CEWP and make the content editor web part hidden.
<!-- jQuery Reference. You can refer it from Layouts Folder/Doc Library too, after uploading the script. -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
 
<!-- Download SPServices from: http://spservices.codeplex.com/ Or use this CDN  -->
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $().SPServices({
  operation: "GetGroupCollectionFromUser",
  userLoginName: $().SPServices.SPGetCurrentUser(),
  async: false,
  completefunc: function(xData, Status) {
  var xml = xData.responseXML.xml;

   //If the current User does belong to the group "Service desk Operators"
    if (xml.search('Service Desk Operators') == -1)
     {
          //   alert("No, User Doesn't Exists!");                   
           $("select[title=Status]").parent().parent().parent().hide();  
          //or use: $('td.ms-formlabel:contains("Status")').parent().hide();
          //You can also use:  $('nobr:contains("Status")').closest('tr').hide();
       }   
    }
 });
});
</script>

Instead of content editor web part, You can also edit the NewForm.aspx or EditForm.aspx file and place the code under "PlaceHolderAdditionalPageHead" to hide fields in SharePoint list forms.

Here is the NewForm.aspx view for "Help Desk Operators" - Note that the "Status" field is visible.
hide sharepoint list columns based on user permissions
 and here is the view for end-users: SharePoint list columns hidden based user permissions.
hide sharepoint list form fields columns based on user permissions


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


Wednesday, July 10, 2013

How to Make SharePoint List Column (Form Field) Read Only

How to make a column read only in SharePoint 2010? Well, There are many ways. Here are some:
  1. Make column read only in SharePoint list programmatically
  2. use jQuery to make SharePoint field read only
  3. Using SharePoint designer to set field read only in list forms.

Programmatically Set SharePoint list field to Read-Only using C# object model code or PowerShell script: 

To make a SharePoint field read-only, We can set the " ReadOnlyField" property of SPField to "True" using either PowerShell script or C# code. Here is how: 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Get the Web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/pmo"
#Get the List
$List = $Web.Lists["Project Metrics"]
#Get the Field 
$Field = $List.Fields["Project ID"]
#Set the field to Read only
$Field.ReadOnlyField = $true
$Field.Update()
See the detailed implementation at: Hide Columns in SharePoint List NewForm, EditForm and DispForms.

But the problem is: As soon as you set "ReadOnlyField" to true, field will be hidden from all list forms and list settings. Instead, make the "ShowInNewForm" and "ShowInEditForm" Properties to False to hide them from NewForm.aspx and EditForm.aspx but still make it visible on list settings and DispForm.aspx.

Alternatively, you can create a Field with ReadOnly Property and add the field wherever required.
$SPSite = Get-SPSite "http://sharepoint.crescent.com"
$SPWeb = $SPSite.RootWeb
$SPcolumn = '<Field Type="Number" DisplayName="Project ID" Required="FALSE" 
               ReadOnly="TRUE" ShowInDisplayForm="TRUE"ShowInViewForms="TRUE" EnforceUniqueValues="FALSE" 
                  Indexed="FALSE" Min="1" Max="10000" Group="Crescent PMO Site Columns" 
                    ID="{b81c7da6-1317-46fa-a32b-9f446c30b6e9}" StaticName="ProjectID" Name="ProjectID"></Field>'
$SPWeb.Fields.AddFieldAsXml($SPcolumn)
See more at: Create Site Column Feature for SharePoint 2010

However, these methods not satisfying our requirement. What we want is the field to be present in all SharePoint list forms with "Read-only" mode! So, lets see help from jQuery solution.

Make a SharePoint List form field read only with jQuery 

To make a column read only, Place the below code in a text file, upload to any SharePoint library, Add a CEWP to the "NewForm.Aspx" and/or "EditForm.aspx" or wherever required. Specify this script as "Content Link" from content editor web part properties pane.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"
       type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function()
{
//Set the Field to Read only and change its background colour
$("input[title='Metrics ID']").attr("readonly","true").css('background-color','#F6F6F6');
//You can disable the field also:  $("input[Title='Metrics ID']").attr("disabled", "disabled");
});

</script>
Output goes like this: SharePoint 2010 read only field in edit form
sharepoint make field readonly in editform
To disable a Choice field (Drop Down) use:
$("Select[Title='Department']").attr("disabled", "disabled");

To Disable Multiline Plain text fields
$("input[Title='Description']").attr("disabled", "disabled");

How to make a field read only in SharePoint Designer:

To make a SharePoint list column read only in EditForm.aspx, follow these steps:
  1. Open the SharePoint site in SharePoint Designer
  2. Navigate to the List. Under the "Forms" section, click on "New"
    how to make a field read only in sharepoint designer
  3. Create a new EditForm by giving it a name, and choosing other properties in the below screen.
    sharepoint designer 2010 read only field
  4. Edit the newly created Edit form in SharePoint designer, Click on the target property to select
  5. Change the "DisplayMode" property from "Edit" to "Display" in the properties pane.
    sharepoint designer 2010 make field read only
  6. Save and close.
Output: Read only field in SharePoint list form using SharePoint Designer
sharepoint designer 2010 read only column
Years back, there was a similar requirement for SharePoint 2007 and I used JavaScript: Make Read-Only fields in SharePoint List Forms using Javascript

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


Monday, July 8, 2013

Find and Delete Orphaned Users in SharePoint with PowerShell

Some time back, I posted an article on Orphaned Users in SharePoint. in short, SharePoint orphaned users are those who are deleted from Active Directory, but still have permissions to SharePoint sites!  Read more here: Find and Delete Orphaned Users in SharePoint

Now, with PowerShell, We can Find and Delete orphaned users in SharePoint. Here is the script: I've made it work with SharePoint 2007 also.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Functions to Imitate SharePoint 2010 Cmdlets in MOSS 2007
function global:Get-SPWebApplication($WebAppURL)
 { 
  return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
 }

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
}

#Function to Check if an User exists in AD
function CheckUserExistsInAD()
   {
   Param( [Parameter(Mandatory=$true)] [string]$UserLoginID )
 
  #Search the User in AD
  $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
  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 ($result -ne $null)
         {
           return $true
         }
  }
  return $false   
 }
 
 $WebAppURL="https://sharepoint.crescent.com"
 #Get all Site Collections of the web application
 $WebApp = Get-SPWebApplication $WebAppURL

 #Iterate through all Site Collections
 foreach($site in $WebApp.Sites)  
    {
 #Get all Webs with Unique Permissions - Which includes Root Webs
 $WebsColl = $site.AllWebs | Where {$_.HasUniqueRoleAssignments -eq $True} | ForEach-Object {
        
        $OrphanedUsers = @()
        
  #Iterate through the users collection
  foreach($User in $_.SiteUsers)
  {
      #Exclude Built-in User Accounts , Security Groups & an external domain "corporate"
   if(($User.LoginName.ToLower() -ne "nt authority\authenticated users") -and
                ($User.LoginName.ToLower() -ne "sharepoint\system") -and 
                  ($User.LoginName.ToLower() -ne "nt authority\local service")  -and 
                      ($user.IsDomainGroup -eq $false ) -and 
                          ($User.LoginName.ToLower().StartsWith("corporate") -ne $true) )
                   {
                    $UserName = $User.LoginName.split("\")  #Domain\UserName
                    $AccountName = $UserName[1]    #UserName
                    if ( ( CheckUserExistsInAD $AccountName) -eq $false )
                    {
                         Write-Host "$($User.Name)($($User.LoginName)) from $($_.URL) doesn't Exists in AD!"
                                    
                                    #Make a note of the Orphaned user
                                    $OrphanedUsers+=$User.LoginName
                    }
                   }
  }
        
        # ****  Remove Users ****#
        # Remove the Orphaned Users from the site
        # foreach($OrpUser in $OrphanedUsers)
        #   {
        #        $_.SiteUsers.Remove($OrpUser)
        #        Write-host "Removed the Orphaned user $($OrpUser) from $($_.URL) "
        #   }
        
 }
} 

Executing this script will scan and give the list of orphaned users in a SharePoint web application. It can be used in SharePoint 2010 also to find & delete orphaned users.

SharePoint orphaned users cleanup:
I've commented out the "Remove Users" section at the bottom of the script.  Just remove # tags to uncomment and execute the script to delete orphaned users in SharePoint.

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


Fix Custom SharePoint 2010 Logo Missing in Web Part Pages

SharePoint 2010 and SharePoint 2007 web part pages doesn't display the custom logo because they override PlaceHolderPageTitleInTitleArea place holder.
logo on sharepoint web part pages
Even though the new logo you applied reflects on all other places, Web part pages are still displaying SharePoint 2010's default logo. Well, Its a known issue. To fix this on web part pages, Navigate to:
  • Site Actions >> Edit the page 
  • Click on "Title Bar Properties" on the Page tab
    set logo on sharepoint web part pages
  • From the properties pane at right, add the URL to your site logo under Image Link
  • Apply to bring Logo on SharePoint 2010 web part pages
While the above steps are fairly simple and feasible for a single page, would be a pain in the *** for site with large amount of web part pages, isn't it? So, Lets do the change at master page level. Here is how:
  • Open the master page in SharePoint designer
  • Find the element: <SharePoint:SiteLogoImage name="onetidHeadbnnr0"  and replace the name attribute from "onetidHeadbnnr0" to something else. (say: onetidHeadbnnr1)
  • Save and close.Check-in/Approve the master page if required.
custom logo on sharepoint 2010 web part pages
Fortunately, This issue is solved in SharePoint 2013!


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


Export SharePoint Users and Groups to Excel using PowerShell

Requirement:
Export SharePoint Users and Groups to Excel for analyzing SharePoint Groups and Users along with their Account Name, E-mails!We can export SharePoint User Group to excel using PowerShell. Here is how:

PowerShell Script to Export Users & Groups:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Using Get-SPSite in 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
}

$URL="http://sharepoint.crescent.com/sites/csaportal/"
 
     $site = Get-SPSite $URL 
   
     #Write the Header to "Tab Separated Text File"
        "Site Name`t  URL `t Group Name `t User Account `t User Name `t E-Mail" | out-file "d:\UsersandGroupsRpt.txt"
        
     #Iterate through all Webs
      foreach ($web in $site.AllWebs) 
      {
        #Write the Header to "Tab Separated Text File"
        "$($web.title) `t $($web.URL) `t  `t  `t `t " | out-file "d:\UsersandGroupsRpt.txt" -append
         #Get all Groups and Iterate through    
         foreach ($group in $Web.groups) 
         {
                "`t  `t $($Group.Name) `t   `t `t " | out-file "d:\UsersandGroupsRpt.txt" -append
                #Iterate through Each User in the group
                       foreach ($user in $group.users) 
                        {
                           #Exclude Built-in User Accounts
                    if(($User.LoginName.ToLower() -ne "nt authority\authenticated users") -and ($User.LoginName.ToLower() -ne "sharepoint\system") -and ($User.LoginName.ToLower() -ne "nt authority\local service"))
                    {
                                "`t  `t  `t  $($user.LoginName)  `t  $($user.name) `t  $($user.Email)" | out-file "d:\UsersandGroupsRpt.txt" -append
                             }
                        } 
         }
       }
    write-host "Report Generated at d:\UsersandGroupsRpt.txt"

This script will Export SharePoint user group to excel. Here is the report output:
Export SharePoint Users and Groups to Excel using PowerShell
 
PowerShell script to Get All Groups and Members of Each group:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Using Get-SPSite in 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
}

$URL="https://sharepoint.crescent/sites/helpdesk/us"
 
     $site = Get-SPSite $URL 
     
     if (Get-SPWeb($url).HasUniqueRoleAssignments -eq $true) 
     {
        $Web=Get-SPWeb($url)
     }
     else
     {
        $web= $site.RootWeb
     }

     #Get all Groups and Iterate through    
     foreach ($group in $Web.sitegroups) 
     {
        write-host " Group Name: "$group.name "`n---------------------------`n"
            #Iterate through Each User in the group
                   foreach ($user in $group.users) 
                    {
                        write-host $user.name  "`t" $user.LoginName  "`t"  $user.Email  | FT
                    } 
     write-host "=================================="  #Group Separator
     }

How to Get members of a particular group in SharePoint 2007 using PowerShell:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Using Get-SPSite in 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
}

$URL="http://sharepoint.crescent.com/sites/operations/"

     $site = Get-SPSite $URL
     $web= $site.OpenWeb()  

     #Get the Group by its name
     $Group = $Web.sitegroups | Where-Object {$_.Name -eq "CSA Test All Entity Users"}
  
            #Iterate through Each User in the group
                   foreach ($user in $group.users)
                    {
                        write-host $user.name  "`t" $user.LoginName "`t"  $user.Email

                    }
Its also possible to read user properties from User Profile.

PowerShell script to Get Members of Each Group at Web (Sub-Site) Level:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$WebURL="http://portal.crescent.com/Teams/sales/"  
$Web = Get-SPWeb $WebURL
 
 #Get all Groups and Iterate through    
 foreach ($group in $Web.groups) 
 {
    #Get Permission Levels Applied to the Group   
    $RoleAssignment = $Web.RoleAssignments.GetAssignmentByPrincipal($group)

    $RoleDefinitionNames=""
    foreach ($RoleDefinition in $RoleAssignment.RoleDefinitionBindings)
    {  
        $RoleDefinitionNames+=$RoleDefinition.Name+";"
    }
    
    write-host "Group Name: $($Group.name) : Permissions: $($RoleDefinitionNames) ----"
    #Iterate through Each User in the group
        foreach ($user in $group.users) 
        {
            write-host $user.name  "`t" $user.LoginName  "`t"  $user.Email  | FT
        } 
 } 
and the output: SharePoint PowerShell export group members
export users from sharepoint group powershell

Related Posts:


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


Friday, July 5, 2013

Import from CSV to SharePoint List with People Picker Field Values

Requirement is: To add bulk of records from a CSV file to SharePoint list with People Picker field of "Allow multiple selections" set to "Yes".

Unfortunately, SharePoint datasheet view doesn't allow us to copy-paste People picker values. So, I got to write the script!

Here is my data to be imported to SharePoint list from CSV file:
Import from CSV to SharePoint List with People Picker Field Values

PowerShell Script to import CSV data to SharePoint list with people picker field
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Functions for Get-SPSite & Get-Web in 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
}

$URL="https://sharepoint.crescent.com/sites/helpdesk/"
 
#Read the CSV file - Map the Columns to Named Header 
$CSVData = Import-CSV -path "D:\csaapprovalmatrix.csv" -Header("Region", "Country", "Company", "Entity", "Preparer", "Reviewers")

#Get the Web
$web = Get-SPWeb $URL
 
#Get the Target List
$list = $web.Lists["CSA Approval Matrix"]
 
#Iterate through each Row in the CSV
foreach ($row in $CSVData)
 {
       $item = $list.Items.Add()
        
       $item["CSA Region"] = $row.Region
       $item["CSA Country"] = $row.Country
       $item["CSA Company"] = $row.Company
       $item["CSA Entity"] = $row.Entity

    #Set "Preparer" People Picker Field value
 try
 {
    $ErrorActionPreference = "Stop"
    
       $Preparer=[Microsoft.Sharepoint.Utilities.SpUtility]::GetLoginNameFromEmail($Web.Site, $row.Preparer)
       [Microsoft.SharePoint.SPUser]$PreparerUser = $Web.EnsureUser($Preparer)       
    }
    catch
    {
     write-host "Could Not resolve Preparer: $($Row.Preparer)" 
        write-host $_.Exception.Message
        continue
    }
    finally
    {
     $ErrorActionPreference = "Continue"
      #continue; #Skip to Next Row from the CSV
    }
  
  $item["CSA Preparer"] =  $PreparerUser  
  
  #Set $Reviewers People picker field with Multiple values allowed
  $ReviewersList = new-object Microsoft.SharePoint.SPFieldUserValueCollection
  $Reviewers = $row.Reviewers -split ';'

  foreach ($Reviewer in $Reviewers)
    {
  if ($Reviewer -ne $null) 
   {
       #Get the Login Name "Domain\User" from Email
     $ReviewerAccount =[Microsoft.Sharepoint.Utilities.SpUtility]::GetLoginNameFromEmail($web.Site, $Reviewer)
                try
                {
                     $ErrorActionPreference = "Stop"
                      
             [Microsoft.SharePoint.SPUser]$ReviewerUser = $Web.EnsureUser($ReviewerAccount)   
               $ReviewerValue = new-object Microsoft.SharePoint.SPFieldUserValue($Web, $ReviewerUser.ID, $ReviewerUser.LoginName)
               $ReviewersList.Add($ReviewerValue)
                }
                catch
                {
                     write-host "Could Not resolve Reviewer: $($Reviewer) "
                     write-host $_.Exception.Message
                     continue
                }
                finally
                {
                     $ErrorActionPreference = "Continue"
                }
   }
 }
    write-host $ReviewersList
 #Skip to Next item if $ReviewersList is null
 if($ReviewersList -eq $null)
 {
  continue
 }
 
    $item["CSA Reviewers"] = $ReviewersList

    $item.update()

}
Another challenge was: CSV has email ids instead user names! So, I used SpUtility's GetLoginNameFromEmail function to get the Login Name from given Email Id.

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


Set SharePoint People Picker Default Value to Current User

Requirement: In a request tracking system, wanted to auto populate people picker value from currently logged in User.

Solution:  How to set the People Picker field value to current user? Lets use jQuery and SPServices to fetch the logged in user name and fill the SharePoint list form's people picker field value.

In short, Call SPServices function: SPGetCurrentUser() to retrieve the get the current user. Populate the people picker In SharePoint List Form using jQuery! Place this script in a text file, upload to any SharePoint library, Edit the NewForm.aspx page by appending ?toolpaneview=2 to the URL, Add a CEWP and locate the script in Content editor web part's property.

<!-- jQuery Reference. You can refer it from Layouts Folder/Doc Library too, after uploading the script. -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
 
<!-- Download SPServices from: http://spservices.codeplex.com/ Or use this CDN  -->
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>

<script type="text/javascript">
 $(document).ready(function() {
     //Get the current user
     var user= $().SPServices.SPGetCurrentUser();
 
      //Set all sharepoint 2010 people picker default to current user
      $("div[title='People Picker']").text(user);
  });
</script>

When we have multiple people picker fields in the SharePoint form, we got to find the one needs to be set.

<!-- jQuery Reference. You can refer it from Layouts Folder/Doc Library too, after uploading the script. -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
 
<!-- Download SPServices from: http://spservices.codeplex.com/  -->
<script type="text/javascript" src="http://sharepoint.crescent.com/helpdesk/support/jquery.SPServices-2013.01.min.js"></script>

<script type="text/javascript">
 $(document).ready(function() {
  
  //Get the current user name 
  var user= $().SPServices.SPGetCurrentUser();
 
   //Find the Specific People picker field "Requester" and set its value 
   $().SPServices.SPFindPeoplePicker({
   peoplePickerDisplayName: "Requester",
   valueToSet: user,
   checkNames: true
  });

  }); 

</script> 
Result in action: Set SharePoint People Picker Default Value to Current User
set sharepoint people picker default value current user

Its also possible to set the people picker from current user Using client side object model


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


Wednesday, July 3, 2013

SharePoint Incoming Email does not Trigger Workflow

Today, created a Nintex workflow to send out E-mail notification to SharePoint groups. Start-up option for the workflow was: "Start when Items are created", but in SharePoint 2007 incoming email didn't trigger the workflow on new item creation.
sharepoint incoming email start workflow
Root cause:
Incoming E-mail attachments are uploaded to SharePoint libraries using "System Account" (If E-mail settings are set to: "Accept e-mail messages from any sender") which will not trigger workflows by design!

What's the Fix for SharePoint workflow not starting on incoming email?
Well, the fix is simple! Just execute this STSADM command line:
stsadm -o setproperty -pn declarativeworkflowautostartonemailenabled -pv true

This fix applies to MOSS 2007 and SharePoint 2010 for incoming email to start workflow. Same fix applies to SharePoint designer workflows also! SharePoint incoming email doesn't trigger workflow by default, It works after the fix.

By default, starting a workflow through incoming email is not enabled. This PowerShell script enables workflow to started automatically when a new item is created.
$SPWebService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$SPWebService.DeclarativeWorkflowAutoStartOnEmailEnabled = $true
$SPWebService.Update()

KB articles addressing this issue: http://support.microsoft.com/kb/953289, http://support.microsoft.com/kb/947284/en-us

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


Tuesday, July 2, 2013

Force Delete Corrupted SharePoint List using PowerShell

I got few corrupted lists when a custom code, which provisions lists got stuck in middle! I couldn't delete the corrupted list neither from SharePoint web interface nor using SharePoint Designer!

When I tried to access the corrupted SharePoint list from browser, received this error message:
"List does not exist. The page you selected contains a list that does not exist. It may have been deleted by another user."

Alright, How to force delete corrupted SharePoint list? To delete corrupted list in SharePoint, we can either use STSADM command line tool or PowerShell.

Delete corrupted list in SharePoint 2007 using STSADM:
We can delete the corrupted list using stsadm forcedeletelist command. Here is how:
Stsadm -o forcedeletelist -url <LIST URL>

SharePoint delete list with PowerShell
We can delete the corrupted list using PowerShell programmatically. Here is the script for SharePoint 2010 to delete corrupted list:
#Get the Web 
$web = Get-SPWeb "<SharePoint-site-URL>"
#Get the corrupted List
$list = $web.lists["corrupted list name"]
#Set the AllowDeletion Flag to True
$list.AllowDeletion = $true
$list.Update()

#Permanently Delete the list
$list.Delete()

#To Send it to Recycle bin, use:  $list.Recycle()

or use this alternate approach: Force delete list SharePoint 2010 PowerShell
Get-SPWeb "http://sharepoint-site-url" | where-object { $_.Lists["corrupted list name"].Delete() }
This removes corrupted list in SharePoint 2010.

BTW, there are other causes for the error: "List does not exist.", I got this error message after a SharePoint migration.
  1. DNS/AAM entries are not properly configured.
  2. User doesn't has access to content type/Document Template which is being used by the list.
  3. Site may be locked! Go to: Central Administration, Site collection quotas and locks to unlock the site.


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


Delete Users from SharePoint Site Collection using PowerShell

So you don't want a particular user to have access to SharePoint 2010 site anymore! Want to delete user from SharePoint 2010 site collection, isn't it? well, How to delete user from site collection?
  1. To delete user in SharePoint 2010, Navigate to the site collection as a Site collection Administrator
  2. Click on Site actions >> Site permissions
  3. Click on any SharePoint group. Now the URL will look some thing like:
    http://your-site-collection-url/_layouts/people.aspx?MembershipGroupID=11.
  4. Change the MemberShipGroupID parameter's value from 11 to 0. i.e. :
    http://your-site-collection-url/_layouts/people.aspx?MembershipGroupID=0 and hit "Enter" key. This will lead you to see All People page.
  5. Select the user you want to delete, and click on Actions >> "Delete user from Site collection"
    sharepoint delete user from site collection powershell
That's it!

By the way, to delete user in SharePoint 2007, "All People" page link is straightforward. Just navigate to: Site Actions >> Site Settings >> Advanced Permissions >> All People (In Quick Launch!)

Delete Users from SharePoint Site Collection using PowerShell:
PowerShell comes really handy in occasions of repeated manual tasks. Lets use PowerShell to delete user from SharePoint 2010 site collection.

PowerShell script in SharePoint 2010 to delete user from site collection
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Root web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/operations"
#Supply the user account 
$UserAccount = "Global\DaveP"
#Removes user from site collection
Remove-SPUser -Identity $UserAccount -Web $Web -Confirm:$False
This PowerShell script deletes a particular user from given site collection. Also it deletes user from userinfo table! Remember, SharePoint cannot delete user if the user is Site collection administrator!!

SharePoint delete user from site collection programmatically using C#:
We can also use C# object model code in SharePoint to delete user programmatically:
   //Define the parameter values: Site collection URL and user account to remove
            string siteURL = "http://sharepoint.crescent.com/sites/operations";
            string userAccount = @"Global\MarkM";

            using (SPSite site = new SPSite(siteURL))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Get the User
                    SPUser user=null;
                    try
                    {
                         user = web.SiteUsers[userAccount];  
                    }
                    catch (SPException ex) {//user Not found in the site collection}
                    
                    //Check if the given user is valid and found in the site collection
                    if (user !=null)
                    {
                        //Remove the user if he is not a Site collection administrator
                        if (!user.IsSiteAdmin)
                        {
                            //Remove the user from site collection
                            web.SiteUsers.Remove(user.LoginName);  
                            Console.WriteLine("User removed from:"+site.RootWeb.Url);
                        }
                    }
                }
            }
            //Pause
            Console.ReadLine();
this removes user completely from SharePoint site collection.

Delete user from all site collections in SharePoint 2010 using PowerShell:
Some times, we may need to delete a particular user from all site collections. Say for e.g. Employee leaves the company!

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function DeleteUserFromAllSites([string]$WebAppURL, [string]$UserAccount, [bool]$ScanOnly)
{
 <#
  .SYNOPSIS
   Function to Search and Delete given user from all site collections of the web application
  .DESCRIPTION
   This PowerShell function Scans each site collection under the all site collections of the given web application
   and deletes the user from site collections.
  .EXAMPLE
   DeleteUserFromAllSites "http://sharepoint.crescent.com" "global\davep" $true
   This example removes the user account "global\davep" from the web application "http://sharepoint.crescent.com"
  .INPUTS
   $WebAppURL - URL of the web application in which the user account to be scaned and or deleted
   $UserAccount - User account to delete from all sites
   $ScanOnly - Indicates whether the script should delete the user or only scan
  .OUTPUTS
   Writes the output on screen: List of site collections from where the user account is found/removed.
 #>

   
   #Get the web application
   $WebApp = Get-SPWebApplication $WebAppURL
   
   #Loop through each site collection
   foreach ($Site in $WebApp.Sites)
   {
    try
           {
      $ErrorActionPreference = "Stop"
      #Try to get the User
      $User = $Site.RootWeb.SiteUsers | Where-Object {$_.LoginName -eq $UserAccount}
      
      #If user account found
      if($User -ne $null)
      {
       if($ScanOnly -eq $true)
       {
        Write-Host "Found user on: $($site.Rootweb.URL)"
       }
       else
       {
          #Remove the User from site collection
          $Site.RootWeb.SiteUsers.Remove($UserAccount)
          Write-Host "User Deleted from: $($site.Rootweb.URL)"
       }
      }
    
     }
    catch
           { 
              #Write error message on screen and to a LOG file
              write-host "Error Deleting user from site collection: $($site.rootweb.url)`n" $_.Exception.Message
              $_.Exception.Message >> "d:\error.log" 
           }
          finally
          {
              $ErrorActionPreference = "Continue"
              $site.Dispose()
          }
   }
}

#Call the function
DeleteUserFromAllSites "http://sharepoint.crescent.com" "global\davep" $true 
This will delete SharePoint user from all site collections in the given web application.

Delete Multiple Users from SharePoint site using PowerShell:
To delete multiple users from all site collections, just store user accounts in an array and call the PowerShell function. E..g
#Array to store user accounts
$userNames= ("domain\user1", "global\salaudeen", "domain\user3")
#Iterate through the array
foreach($user in $userNames)
 {  
   #Call the function
   DeleteUserFromAllSites "http://sharepoint.crescent.com" $user $true 
 }


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


How to Run C# Code from PowerShell

Some time back, I wrote C# code for SharePoint Administration Governance purpose: Find Large Lists & Generate Report in SharePoint , which actually scans all lists in all sites and creates a report in CSV format.

I feel PowerShell is more convenient than C# for couple of reasons:
  • Because, PowerShell is quite powerful and more flexible administration and automation tool
  • Although C# is good for typical Software development, for such small tasks C# project is overkill!
  • Its faster to write, deploy and change it in PowerShell than creating a project in Visual Studio, compiling it, deploying it to the target, correcting the code, compiling it again, deploying it again!
So, I wanted to leverage the existing C# code. While the code is relatively simpler to rewrite in PowerShell, Found another interesting way to run C# code in PowerShell. Here is an example:

#Assemblies to Reference 
$Assembly = (
    "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" ,
    "Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
    );

# C# Source Code 
$SourceCode = @"
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
 
namespace SPGovernance
{
    public class AdminReports
    {
        public static void GenerateLargeListsReport(string siteCollURL)
        {
         SPSite site = new SPSite(siteCollURL);
   StreamWriter SW;
   
   //Enumerate through each sub-site
            foreach (SPWeb web in site.AllWebs)
                {
                    foreach (SPList list in web.Lists)
                    {
                        if (list.ItemCount > 2000)
                        {
                            //Log the details to a file
                            SW = File.AppendText("c:\\LargeListsInfo.csv");
                            SW.WriteLine(list.Title + "," + web.Url  + list.DefaultViewUrl + "," + list.ItemCount);
                            SW.Close();
                        }
                    }                
   
             }
    Console.WriteLine("Large Lists Reports has been Generated!"); 
        }
    }
}
"@

#Add the Assembly
Add-Type -ReferencedAssemblies $Assembly -TypeDefinition $SourceCode -Language CSharp

#Call the function from Assembly
[SPGovernance.AdminReports]::GenerateLargeListsReport("http://sharepoint.crescent.com/sites/Sales") 

One limitation is: You may get "Add-Type : Cannot add type. The type name 'SPGovernance.AdminReports' already exists" error message if you try to execute the code more than once. This is a known limitation and you have to launch a new PowerShell window and execute the code.

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


Monday, July 1, 2013

Membership Web part on SharePoint My Sites is not Updated

Problem: Membership Web part on SharePoint My Sites is not Updated! still displays old data.

Solution: Trigger a user profile Full import! That will update membership web part on SharePoint My sites! Here is how:
  • Go to Central Administration >> Pick the relevant Shared Service Provider
  • Click on "User profiles and properties"
  • Click on "Start full import" link
    sharepoint group membership web part not updated
  • Watch and wait for the profile import to complete.
Once the profile import is completed, your membership should be updated!

If you are not getting "Start Full Import" link, which simply means, your profile import is either in progress or Stuck!

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


Content Editor Web Part Content Link Redirect - 404 Page Not Found Error

Problem: A particular SharePoint site's Home page URL leads to 404 page not found error. While all other pages were working without any issues, On hitting the Home page URL, observed its redirecting to some other URL which doesn't exists!

Root cause:
Usually these kind of redirects are placed in CEWP using JavaScript. So, opened the page in SharePoint designer, tried locating the script, But could not find any such things.

After an hour, found the problem. Actually user has placed a content editor web part and set the "content link" as an external web site's URL. That external web site URL was redirecting to some other URL on page load, which altered the actual SharePoint site URL. See the screen above:
Solution: Simple! Delete the content editor web part with "Content link" pointing to a site, which redirects! just append ?contents=1 to the SharePoint site URL and close/delete the web part in Web part maintenance page.

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


Add a Link to Site Settings Page in SharePoint 2010

There was a requirement to get list owners info who created the lists, we developed a custom application page in SharePoint 2010: How to Create Custom Application Page in SharePoint 2010 to get List Owners

But the link to the application page to be placed somewhere in the site for an easy access by site owners, isn't it? Where to link it? Site settings page would be the ideal place for such things! So lets add a link to site settings page in SharePoint 2010.

SharePoint 2010 add link to site settings page
1. Create a new "Empty SharePoint Project" Farm Solution in Visual Studio 2010. Give it a Name.
add link to site settings page sharepoint 2010

2. Add an Empty Element to the Project. This will add "Elements.xml" file to the solution.
add link to site settings sharepoint

3.  Update the Elements.xml file with the below code: This adds group to site settings as well as add link in site settings page in that group.

  <!-- Add a Custom Group "Site Owner Reports" under Site Actions -->
    <CustomActionGroup Description="Group for Site Owner Reports" Id="Crescent.SiteOwnerReports"
       ImageUrl="/_layouts/images/crescent-rpt-48.png" Location="Microsoft.SharePoint.SiteSettings"
  Sequence="100" Title="Site Owner Reports">
  </CustomActionGroup>

  <!-- Add a Link under the Group "Site Owner Reports" in Site Actions -->
    <CustomAction GroupId="Crescent.SiteOwnerReports" Id="UserInterfaceCustomActions.SiteSettings" 
   Location="Microsoft.SharePoint.SiteSettings" Sequence="20" Title="List Owners Info">
       <UrlAction Url="~site/_layouts/CrescentReports/ListOwners.aspx" />
  </CustomAction>
Now the Elements.xml file should look like:
sharepoint 2010 add custom site settings
4. Add an Icon image to mapped "Images" folder. This image will display in site settings links group.

5. Rename the Feature Title and Description through Feature Designer.
sharepoint 2010 add group to site settings

 6. Deploy the Project. Tha's all, We have added link to site settings page in SharePoint 2010. See the result in action:
sharepoint 2010 add link to site settings page
Location & ID parameters are the key in above Elements.xml to add link to site settings page in SharePoint 2010. They defines where the custom group or link should appear. You can place a link to any existing group by supplying its GroupID value.
  • E.g. To add a link under Site collection Administration group of site settings, Provide the Group ID as "SiteCollectionAdmin"
  • To add a link to site settings under "Look and Feel", the Group ID goes like "Customization"
If you want to add a custom group and link in SharePoint 2007, Refer: Add a Link to Site Settings Page in SharePoint 2010. For all available Locations, Refer MSDN: Default Custom Action Locations and IDs

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


You might also like:

Related Posts Plugin for WordPress, Blogger...