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

Download All Files From a SharePoint Library Programmatically using PowerShell

$
0
0
Ever wanted to download all files from a SharePoint Library (Document Library, Picture Library, etc) to your local drive?

While downloading a single file or document is fairly straight forward by Clicking "Download a Copy" from documents Tab of the Ribbon or From the ECB Menu of the document  >> Send To >> "Download a Copy", downloading Multiple files or a complete folder is not that easy when the files count is high.

Sure, Explorer view can do it! Go to the Document Library and choose Explorer View from the Ribbon
Download All Files From a SharePoint Library Programmatically using PowerShell
Now you can drag & Drop (or Copy & Paste) folders, Files from and to your local drive from SharePoint. You can also use map your SharePoint libraries to network drive. 

But How about downloading all documents from all document libraries? Yes, PowerShell can do it well!

PowerShell Script to download all files and folders from a SharePoint Library along with its Structure:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

# Function to Download All Files from a SharePoint Library
Function DownloadFiles($SPFolderURL, $LocalFolderPath)
{
        #Get the Source SharePoint Folder
        $SPFolder = $web.GetFolder($SPFolderURL)


        $LocalFolderPath = Join-Path $LocalFolderPath $SPFolder.Name 
        #Ensure the destination local folder exists! 
        if (!(Test-Path -path $LocalFolderPath))
        {    
             #If it doesn't exists, Create
             $LocalFolder = New-Item $LocalFolderPath -type directory 
        }

	    #Loop through each file in the folder and download it to Destination
	    foreach ($File in $SPFolder.Files) 
	    {
	        #Download the file
	        $Data = $File.OpenBinary()
		$FilePath= Join-Path $LocalFolderPath $File.Name
	        [System.IO.File]::WriteAllBytes($FilePath, $data)
	    }

    	#Process the Sub Folders & Recursively call the function
        foreach ($SubFolder in $SPFolder.SubFolders)
        {
           if($SubFolder.Name -ne "Forms") #Leave "Forms" Folder
             {
                  #Call the function Recursively
                  DownloadFiles $SubFolder $LocalFolderPath
             }
        }
    }

#Get the Source Web
$Web = Get-SPWeb "http://sharepoint.crescent.com/sites/Operations"
 
#Get the Source SharePoint Library's Root Folder
$SourceLibrary =  $Web.Lists["Design Documents"].RootFolder

#Local Folder, where the Files to be downloaded 
$DestinationPath = "C:\Test" 

#Call the Download Files Function
DownloadFiles $SourceLibrary $DestinationPath

The above code is pretty simple. We can re-write this in C# Object model code, Add a Custom Ribbon item to download all files.

Building Charts in SharePoint with Google Charts API

$
0
0
Looking for a quick way to build Charts & Graphs from SharePoint list data? Here is the quickest way to create charts on SharePoint with Google Chart API!
  1. Go to: http://usermanagedsolutions.com/SharePoint-User-Toolkit/Pages/Pie-Bar-Chart-Connector.aspx Building Charts in SharePoint with Google Charts API
  2. Provide "Edit view " URL in the given Text box. E.g. I've a List "Q1Summary" in Finance site collection. Edit view URL is: http://sharepoint.crescent.com/sites/finance/Q1Summary/_layouts/ViewEdit.aspx?List=%7BB9E23283%2DC445%2D4918%2D9229%2DB918FC2D71E2%7D&View=%7BB5A76744%2D98ED%2D422B%2D807A%2DCCBF1BF1F070%7D
  3. Specify other optional parameters such as Chart Type (Pie Chart, Bar, Column), Width, Chart title to generate chart code. Place the generated Chart code in Content editor web part
The code generated would look like:
<div id="spChart"></div><script src="//www.google.com/jsapi" type="text/javascript"></script><script type="text/javascript">

/* 2012 * Christophe Humbert * http://usermanagedsolutions.com/SharePoint-User-Toolkit/ */
(function(){

var options={
chartType: "Bar",
title:"Chart title",
is3D:false,
width:500,
height:300,
url:"/sites/finance/q1summary/_vti_bin/owssvr.dll?Cmd=Display&XMLDATA=TRUE&List=%7BB9E23283%2DC445%2D4918%2D9229%2DB918FC2D71E2%7D&View=%7BB5A76744%2D98ED%2D422B%2D807A%2DCCBF1BF1F070%7D"
};

var o=options,URL=o.url+"&_ts="+(new Date()).getTime(),c=document.getElementById("spChart");c.id="";google.load('visualization','1.0',{'packages':['corechart']});var x=new XMLHttpRequest();x.onreadystatechange=function(){if (x.readyState==4){if (x.status==200){var xml=x.responseXML,r=(xml.getElementsByTagNameNS)?xml.getElementsByTagNameNS("*","row"):xml.getElementsByTagName("z\:row");google.setOnLoadCallback(dC(r));}}};x.open("GET",URL,true);x.send(null);function dC(r) {var d=new google.visualization.DataTable(),a=r[0].attributes,aC=a.length;for (var i=aC-1;i>=0;i--) {if (a[i].name.indexOf("Title")>=0) {var tA=a[i].name;} else {var vA=a[i].name;}}d.addColumn('string',tA.replace(/ows_/,""));d.addColumn('number',vA.replace(/ows_/,""));var rC=r.length,rs=[];for (var i=0;i<rC;i++) {(function(){var arr=[];arr[0]=r[i].getAttribute(tA);var n=r[i].getAttribute(vA).split("#");arr[1]=parseFloat(n[1]||n[0]);rs.push(arr);})();}d.addRows(rs);var chart=(o.chartType=="Pie")?new google.visualization.PieChart(c):(o.chartType=="Bar")?new google.visualization.BarChart(c):new google.visualization.ColumnChart(c);chart.draw(d,options);}})();</script>

That's it! See the result in action: Here is an SharePoint Google chart example
google chart sharepoint 2007
Google charts in SharePoint 2007

Get Query String and Set List Form Field Value using jQuery

$
0
0
Years back, I used JavaScript for the similar requirement in SharePoint 2007: Get the value from URL Query String and populate the value of SharePoint list form field: How to Get the Query String from URL and Set SharePoint List Form field value?

Now in SharePoint 2010, lets use jQuery to get query string from URL and populate list form field's value and SharePoint designer Quick Step to pass the query string value to target URL.

Scenario: We've a "Projects" list with list of projects, and "Project Metrics" list to capture project metrics.We need to add project metrics to the projects from a context (ECB) menu item from Projects list.

Overall Idea:
  1. Lets add a Quick Step using SharePoint designer to pass query string. 
  2. On clicking the Quick Step Link, say "Add Project Metrics", It navigates to the NewForm URL of Project Metrics list with QueryString "ProjectID".
  3. Lets get the query string from URL and set the NewForm's "Project ID" field of Project metrics list item. 
Get Query String and Set List Form Field Value using jQuery
Add a Quick Step in SharePoint Designer:
Create a new Quick Step in SharePoint designer with "Navigate to URL" selected. Enter the below code in it, to navigate to NewForm.aspx file of Project Metrics list with ProjectID value in URL.
javascript:SP.UI.ModalDialog.showModalDialog({url:"/Lists/ProjectMatrics/NewForm.aspx?ProjectID={ItemId}",dialogReturnValueCallback:
 function(dialogResult, returnValue) { 
SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK) }}) 
sharepoint list newform query string
Get Query String and Populate List Form Field Value
In NewForm.aspx of the Project Metrics list, Add a CEWP and link to the below script. Basically, it fetches the Query string "ProjectID" from URL and sets the "Project ID" field in Project metrics list item.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script><script language="javascript" type="text/javascript">

         $(document).ready(function() {

            //Get the Query string value
            var qs = getQueryString('ProjectID'); 

            //Set the Value of "ProjectID" field
     $("input[Title='Project ID']").val(qs);

            //Disable "Project ID" field
     $("input[Title='Project ID']").attr("disabled", "disabled");
         //You can also make the field read-only: $("input[Title='Project ID']").attr('readonly','true');

   });

          //Function to Get Query String from URL
          function getQueryString(key){
            var regex=new RegExp('[\\?&amp;]'+key+'=([^&amp;#]*)');
            var qs=regex.exec(window.location.href);
            return qs[1];
          }

          //Clear the "Disabled" property on Save. If its not enabled, Mandatory field validation fails
   function PreSaveAction() {
     $("input[Title='Project ID']").attr("disabled", "");
     return true;
   }

         </script>
Result: Project ID field is populated from the query string ProjectID from URLsharepoint set field value query string

Set Content Editor Web Part (CEWP) Content with PowerShell

$
0
0
Scenario:
We've a Project site collection with 100's of sub sites created for each project from a custom site template. Home page of each site has a content Editor web part with some content in it, titled "Dashboard Links". Years later, business wanted to change the content in the "Dashboard Links" in each site!

So, Here the requirement is to set the Content Editor web part's content in all sub sites. Lets use PowerShell to automate:

Set Content Editor Web Part (CEWP) Content with PowerShell
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Site collection
$site=Get-SPSite "http://sharepoint.crescent.com/PMO/"

#Loop throgh each subsite in the site collection
foreach($web in $Site.AllWebs)
{
  #Get the Default.aspx file
  $file= $web.GetFile($web.Url +"/SitePages/Home.aspx")

  if($file.Exists)
    {
     #Web Part Manager to get all web parts from the file
     $WebPartManager = $web.GetLimitedWebPartManager( $file,  [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
 
     #Iterate through each web part
     foreach($webPart in $WebPartManager.WebParts) 
      {
        # Get the Content Editor web part with specific Title
        if( ($webPart.title -eq "Dashboard Links") -and ($webPart.GetType() -eq [Microsoft.SharePoint.WebPartPages.ContentEditorWebPart]) )
        {
           #Content to be Placed inside CEWP
           $HtmlContent= "<ul><li><a href='/pmo/dashboard/team-allocation.aspx'>PMO Team Allocation</a></li><li><a href='/pmo/dashboard/bi-dashboard.aspx'>PMO Business Intelligence Dashboard</a></li><li><a href='/pmo/dashboard/pmi-admin.aspx'>PMO PMIS Admin</a></li><li><a href='/pmo/dashboard/pmo-yammer.aspx'>PMO on Yammer</a></li></ul>"

           $XmlDoc = New-Object System.Xml.XmlDocument
     $contentXml=$xmlDoc.CreateElement("content") 
           $contentXml.InnerText= $HtmlContent

           #Set content and Save
           $webpart.Content = $contentXml     
           $webPartManager.SaveChanges($webPart);
         }
      }
    }
 }

Add a Link to Site Settings Page in SharePoint 2010

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

How to Run C# Code from PowerShell

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

Import from CSV to SharePoint List with People Picker Field Values

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

Export SharePoint Users and Groups to Excel using PowerShell

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

                    }
Related Posts:

Find and Delete Orphaned Users in SharePoint with PowerShell

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

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

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

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

Delete All Document Versions in SharePoint Document Library using PowerShell

$
0
0
Requirement is to : Delete all old document versions in SharePoint site collection to free-up some disk space occupied by document versions.

Here is the PowerShell script to delete all document versions in a site collection:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Get the Site Collection
$site = Get-SPSite "http://sharepoint.crescent.com/sites/operations"

#Loop through all sites in the site collection
foreach($web in $site.AllWebs)
{
  #Iterate through all Lists
  foreach($List in $Web.Lists)
 { 
 #Get only document libraries & Skip Hidden 
  if( ($List.BaseType -eq "DocumentLibrary") -and ($List.EnableVersioning) -and ($List.Hidden -eq $false) -and($List.IsApplicationList -eq $false) ) 
     {   
   #loop through each item
      foreach ($item in $list.Items)
      {
    if($item.File.Versions.Count -gt 0)
    {
        # delete all versions
     Write-Host "Deleting $($item.File.Versions.Count) Version(s) on: $($web.URL)$($item.URL)"
      $item.file.Versions.DeleteAll()
    }
      }
  }
 }
 }
$site.Dispose()
Write-Host "Script execution Completed!"
This PowerShell script will delete old versions in SharePoint document libraries for the entire site collection.

Related posts:
Checkout my codeplex tool to cleanup document versions in SharePoint: Download SharePoint Versioning Manager from CodePlex

Hide SharePoint List Columns based on User Permissions

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

How to Prevent SharePoint List or Columns from Deletion

$
0
0
Scenario: We've a configuration list being used by a custom SharePoint application and we don't want to let the users to delete the configuration list in SharePoint. So how to prevent delete in SharePoint list?

The idea is: Set the "AllowDeletion" property of the SharePoint list or Library to false. These properties can be set programmatically using object mode code C# or PowerShell.

PowerShell script to make SharePoint List/Library deletable:
#Get the Web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/pmo"

#Get the List
$list = $web.Lists["Design Documents"]

#Set the "AllowDeletion" property
$List.AllowDeletion=$false
$List.Update()

"Delete this document library" or "Delete this list" link will go hidden under list settings!
sharepoint 2010 delete this list option missing

We can use the C# code as well to disable delete option on SharePoint list and libraries:
using(SPSite site = new SPSite("http://sharepoint.crescent.com/sites/pmo"))
 {
  using(SPWeb web = site.OpenWeb())
   {
       SPList list = web.Lists["Design Documents];
       list.AllowDeletion = false;
       list.Update();
    }
 }

Same trick applies to SharePoint list columns as well. Sett the field's "AllowDeletion" property to false to prevent the field from deletion. Here is an example: Typical SharePoint list columns will look like:
Lets prevent the column from deletion by setting "AllowDeletion" property to false.

PowerShell script to disable delete on list columns:
#Get the Web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/pmo"

#Get the List
$list = $web.Lists["Design Documents"]

#Get the column
$column = $list.Fields["Category"]

#Disable Delete
$column.AllowDeletion = $false
$column.Update()
 
$web.Dispose()
Output:
sharepoint 2010 unable to delete list column

Unable to delete list column in SharePoint 2010? Her is how to delete SharePoint list column programmatically with PowerShell
In some cases, columns added through "Add existing columns" doesn't provide the option to delete! To make them deletable, just revert these two propertis: AllowDeletion & Sealed.
#Get the Web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/pmo"

#Get the List
$list = $web.Lists["Design Documents"]

#Get the column
$column = $list.Fields["Category"]

#Disable Delete
$column.AllowDeletion = $true
$column.Sealed = $false
$column.Update()

#To delete a SharePoint list column in PowerShell, use: $column.Delete() 

$web.Dispose() 
We can also make fields to "Sealed, So that nobody can change the field settings.
Its also possible to make the field as sealed as well as non-deletable, so that the field look like:
sharepoint list sealed and non-deletable columns
SharePoint Manager tool  can be used to set these properties. Just navigate to the site, list or library and set the "AllowDeletion" property to false, save the changes. This hides delete option in SharePoint list.sharepoint list disable delete

How to Run SQL Server Query from PowerShell Script

$
0
0
For a migration project, there was a requirement to read from SQL Server table data , process the migration and then insert / update the tables back from PowerShell. We got to run SQL Server query from PowerShell. Here is how to query SQL Server using PowerShell:

Using PowerShell to query SQL Server
Function QuerySQLServer([string]$DBServer, [string]$DBName, [string]$Query)
{<#
  .SYNOPSIS
   Queries SQL Server from PowerShell
  .DESCRIPTION
  This PowerShell function Queries SQL Server from PowerShell
 .EXAMPLE
  QuerySQLServer "G1VWFE01" "MigrationDB" "SELECT [SourceSiteUrl], [TargetSiteUrl], [SiteType] FROM [MigrationData]"
      This example Gets table entries from the database "MigrationDB" in server "G1VWFE01"
 .INPUTS
  DBServer - Name of the Database Sever where the  target database is located
  DBName - Name of the Database from which the query to be executed
         Query - Query to Execute
 .OUTPUTS
  Rows from the prodefined table "MigrationData"
 #>

 try
        {
  $ErrorActionPreference = "Stop"
  
  #Connection object
  $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
  $cn.open() 

  #SQL Query to retrieve Table rows
  $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
  $reader = $cmd.ExecuteReader()
                #Process the Data
   while ($reader.Read()) 
    {
        #Iterate through Rows
      for ($i = 0; $i -lt $Reader.FieldCount; $i++) 
      {
          #Retrieve the Field (Column) values
          $Reader.GetValue($i)
      }
    }
   }
 catch
        { 
     #Write error message on screen and to a LOG file
            write-host $_.Exception.Message
     $_.Exception.Message >> "d:\error.log"
        }
        finally
        {
            $ErrorActionPreference = "Continue"
        }
 }
#Call the function
QuerySQLServer "GIS-WFE01" "MigrationData"
     "SELECT [SourceSiteUrl], [TargetSiteUrl], [SiteType] FROM [MigrationSiteMapping]"
Its also possible to process the Queried data like:
  Function ProcessSQLServerData([string]$DBServer, [string]$DBName, [string]$Query)
     {
 try
        {
  $ErrorActionPreference = "Stop"
  #Connection object
  $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
  $cn.open() 

  #SQL Query to retrieve Table rows
  $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
  $reader = $cmd.ExecuteReader()
                #Process the Data
   while ($reader.Read()) 
    {
      for ($i = 0; $i -lt $Reader.FieldCount; $i++) 
      {
          #Retrieve the parameters from SQL Server "MigrationMapping" table
          $SourceSiteUrl = $Reader.GetValue(0)
       $TargetSiteUrl =$Reader.GetValue(1)
       $SiteType = $Reader.GetValue(2)

       #Check the SiteType
       if($SiteType  -eq "client")
       {
           Write-Host "Processing Client Site URL: $($SourceSiteUrl)"
                                                            #call a PowerShell function from an External script to process the given parameters
           MigrateClientSite $SourceSiteUrl $TargetSiteUrl
       }
       else #it a Case site
       {
           Write-Host "Processing Case Site URL: $($SourceSiteUrl)"
           #call a PowerShell function from an External script to process the given parameters
           MigrateCaseSite $SourceSiteUrl $TargetSiteUrl
       }
      }
    }
   }
 catch
        { 
     #Write error message on screen and to a LOG file
            write-host $_.Exception.Message
     $_.Exception.Message >> "d:\error.log"
        }
        finally
        {
            $ErrorActionPreference = "Continue"
        }
 }
The above PowerShell SQL Server query example retrieves and process the SQL server table rows.

Powershell script Execute  SQL Server Query performs Insert/Update:
Similarly, for Insert and update, the PowerShell script goes like:
Function RunSQLQuery([string]$DBServer, [string]$DBName, [string]$Query )
{<#
  .SYNOPSIS
   Executes SQL Query, such as Insert, Update, Delete, etc 
  .DESCRIPTION
   This PowerShell function executes the provided SQL query on the provided Database.
  .EXAMPLE
   powershell sql server query update: " RunSQLQuery "G1VWFE01" "MigrationData" "UPDATE [Table-name] SET [SiteStatus]='CREATED' WHERE [SiteID] = '$SiteID' AND [Category] = '$Category' "
                 powershell sql server query insert: use the SQL query as: "INSERT INTO [TableName] ( [SourceSiteUrl], [TargetSiteUrl],  [SiteType] ) VALUES ('http://sharepoint2007.crescent.com','http://sharepoint2010.crescent.com', 'case')"
  .INPUTS
   DBServer - Name of the Database Sever where the "LVMAdmin" database is located
   DBName - NameNo value of the cases table
   Query - Query to execute. Such as Insert, Delete
  .OUTPUTS
   None
 #>
 try
        {
  #Connection object
  $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
  $cn.open() 

  $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query, $cn)
  $cmd.ExecuteNonQuery()
 }
 catch
        {
               #Write error message on screen and to a LOG file
               write-host $_.Exception.Message
  $_.Exception.Message >> "d:\error.log"
        }
        finally
        {
            $ErrorActionPreference = "Continue"
        }
}
This will run SQL Server query from PowerShell.

Delete Users from SharePoint Site Collection using PowerShell

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

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", "me\salaudeena", "domain\user3")
#Iterate through the array
foreach($user in $userNames)
 {  
   #Call the function
   DeleteUserFromAllSites "http://sharepoint.crescent.com" $user $true 
 }

Remove user from SharePoint group:
From SharePoint Web interface, if you want to remove user from SharePoint group, simple navigate to the target group, select the user, click on Actions >> Choose "Remove users from Group"

Delete user from SharePoint group programmatically: If you want to remove user from group programmatically, This PowerShell script can help:
function RemoveUserFromGroup($SiteURL, $GroupName, $UserAccount)
{
 try
    {
     $ErrorActionPreference = "Stop"
  #Get the Web
  $web=Get-SPWeb $SiteURL
  #Get the User to Remove 
  $User  = Get-SPUser -Identity $UserAccount -Web $web

  #Get the Group by its name
  $Group = $Web.sitegroups | Where-Object {$_.Name -eq $GroupName}
  if($Group -ne $null)
  {
    $Group.RemoveUser($User)
    Write-Host "$($User) Removed from the Group: $($GroupName)"
  }
 }
 catch
    { 
   #Write error message on screen and to a LOG file
            write-host $_.Exception.Message
    }
 finally
    {
            $ErrorActionPreference = "Continue"
    }
}

#Call the function
RemoveUserFromGroup "http://sharepoint.crescent.com/sites/Operations" "Operations Members" "Corp\DaveP"

This will remove user from SharePoint group.

Force Delete Corrupted SharePoint List using PowerShell

$
0
0
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()    #Delete the list    $list.Delete()

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.

Set SharePoint People Picker Default Value to Current User

$
0
0
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, 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 Userset sharepoint people picker default value current user

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

How to Rename SharePoint Web Application Name and URL

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

SharePoint Incoming Email does not Trigger Workflow

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

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

Recover SharePoint 2007 / 2010 Product Key using PowerShell

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

Thanks to http://powershell.com/cs/blogs/tips/archive/2012/04/30/getting-windows-product-key.aspx for the idea!
Viewing all 1058 articles
Browse latest View live


Latest Images

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