Friday, 13 March 2015

Powershell for downloading files step by step from sharepoint document library

Below Powershell will download the file Test.pdf from List/Document library name "DocName" in Root folders named A,B and C (You can change the letters in powershell script).


if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$destination = "L:\Data\"
$web = Get-SPWeb -Identity "https://TestWebApp/"
$list = $web.GetList("https://TestWebApp/Test/DocName") #your List/Document Library path

function ProcessFolder
{
    param($folderUrl)
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files)
   
    {
   
         if($file.Name.Contains("Test.pdf"))
            {                                    
                 [Microsoft.SharePoint.SPFileVersion]$iv = $file.Versions[0];
                 $versionNumber = $iv.VersionLabel;    
                                   
             
               Write-Host    $versionNumber.Name
               if($versionNumber )
               {
             
               DownloadFile($iv)
               }
               else
               {
           
               DownloadFile($file)
               }
             }

      else
               {
         
               DownloadFile($file)
               }
                               

       
       }

    }
 

     Function DownloadFile($type)
     {
     try
     {
      $destinationfolder = $destination + "/" + $folder.Url
      if (!(Test-Path -path $destinationfolder))
        {
           $dest = New-Item $destinationfolder -type directory
         }

     $binary = $type.OpenBinary()
     $stream = New-Object System.IO.FileStream($destinationfolder + "/" + $file.Name), Create
     $writer = New-Object System.IO.BinaryWriter($stream)
     $writer.write($binary)
     $writer.Close()

     }
     Catch
     {
      Write "Error: $file.name: $_" >>"L:\Data\Error.txt"
      continue;
     }

     }
       
        #Ensure destination directory


function ProcessAllSubfolders($folderCollection)
{
    foreach ($folder in $folderCollection)
    {
        if ($folder.SubFolders.Count -gt 0)
        {
            ProcessAllSubfolders($folder.SubFolders)
        }

        ProcessFolder($folder.Url)
    }
}


#Download root files
#ProcessFolder($list.RootFolder.Url)
#Download files in folders

foreach($folder in $list.RootFolder.SubFolders)
{
if($folder.Name.StartsWith("A") -or $folder.Name.StartsWith("B") -or $folder.Name.StartsWith("C"))
{
ProcessFolder($folder.Url)

if ($folder.Subfolders.Count -gt 0)
        {
            ProcessAllSubfolders($folder.SubFolders)
        }

}

}

Write-Host "Completed Succesfully"


 
 

Powershell for migrating users in claims in sharepoint

Following powershell will migrate classic mode users into Claim based in sharepoint

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$WebAppName = "https://testspsite/"

$wa = get-SPWebApplication $WebAppName

#Final step is to trigger the user migration process
$wa = get-SPWebApplication $WebAppName
$wa.MigrateUsers($true)

Thursday, 12 March 2015

List Threshold Limits & Workarounds in Sharepoint

Minimum Limit is 2000 and Maximum limit is 2147483647
list view threshold by default is 5000 and 20000 for auditors and administrators.
Effect on performance :The limitation actually comes from sql server. if SQL Server executes a query on a single table that would exceed 5,000 results, SQL Server will lock the entire table while the query executes. Since SharePoint stores all list data in a single table, a single query that returns over 5,000 items will lock all of the list and library data for that entire content database! Users who are accessing content in SharePoint while the SQL Table is locked will have to wait longer for their results to be returned.
Avoiding List Threshold Issues:
By carefully configuring your list views, you can return the data that users need to see while keeping under your threshold limits for that list or library. Here are some tips to consider while planning the structure for your content.
•Separate your content into multiple lists and libraries.

•Create multiple list views. Each view can show the content in
different ways allowing users to choose what they prefer to see.
Some common example may include Recently Changed, Recently Added,
Created By Me, Assigned to Me, Due Today.

•Add filters to your list views to limit the content that is
returned.

•Use “AND” when defining your filters. Choosing “OR” will return all
results first before your filter is applied.

•The first criteria in your view filters should have the greatest
impact on reducing the number of items returned.

•Add an Index to any columns used for sorting or filtering your
views. SharePoint automatically works some magic in SQL Server when
you create an indexed column which allows it to quickly analyze and
return values, bypassing thresholds.

Wednesday, 11 March 2015

Powershell for migrating Users in sharepoint 2010 to another domain

Below powershell script is used to migrate users from one domain to another in sharepoint 2010.



 if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}



$users = Get-SPUser -web http://cp2010:6070/

foreach ($User in $Users) {
$domainName=$user.loginname.split('\')[0]
$userName=$user.loginname.split('\')[1]

if ($domainname -eq 'Test1')
{
#write-host $userName
$name='Test2\'+$userName
Move-SPUser -IgnoreSID -Identity $user -NewAlias $name
}
}


Just replace the Test1 to your old domain name and Test2 with your new domain name

Migrate Active Directory group in Sharepoint 2013 Using PowerShell

Below Powershell Script migrates AD group in one domain to another in Sharepoint 2013



if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

 $farm = Get-SPFarm

$farm.MigrateGroup('TestDomain1\Group', 'TestDomain2\Group')


Branding Mysite with feature stapling in Sharepoint 2013


Here is a quick guide for branding SharePoint 2013 My Sites using Feature Stapling.






Create a new Sharepoint Solution.


Select "Farm solution" then provide the correct URL to your MySite Host (in my case I'm using "/my") then click Finish.

Step 1 : Provisioning the custom masterpage


Add a new Module to the projet.


As a starting point just copy the original my sites masterpage from "\15\TEMPLATE\FEATURES\MySiteMaster\mysite15.master" into the project and rename it "CustomMySite.master" and integrate your HTML/CSS design to it. EDIT : if you are adding a new file (css, png, jpg,...) that you are referencing in the master consider using the LAYOUTS folder to keep url reference simple. Alternatively you can use a provisioning feature to store it in a library instance on the site but this method can be unsafe as the url may be inconsistent and therefore will require to unghost the masterpage to edit the html.

Edit the Elements.xml and copy this:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="ML_MasterPages" List="116" Url="_catalogs/masterpage" Path="ML_MasterPages" RootWebOnly="TRUE">
    <File Url="CustomMySite.master" Type="GhostableInLibrary" />
  </Module>
</Elements>



You'll have to add the module to the feature you will create in step 2.

Step 2 : Applying the custom masterpage to the site
We'll use an event receiver to apply the new master.


Add a new Feature with scope "Site" and name it "Site_ApplyCustomMasterPage";


Add an event receiver to the feature.

Add the following code:

namespace ClientName.MySitesBranding.Features.Site_ApplyCustomMasterPage
{
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using System;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;

    [Guid("{your Guid}")]
    public class Site_ApplyCustomMasterPageEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite siteCollection = (SPSite)properties.Feature.Parent;
            string masterUrl = SPUrlUtility.CombineUrl(siteCollection.ServerRelativeUrl, "_catalogs/masterpage/CustomMySite.master");

            foreach (SPWeb web in siteCollection.AllWebs)
            {
                try
                {
                    web.MasterUrl = masterUrl;
                    web.CustomMasterUrl = masterUrl;
                    web.Update();
                }
                catch
                {
                    if (web != null)
                        web.Dispose();

                    throw;
                }

                if (web != null)
                    web.Dispose();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite siteCollection = (SPSite)properties.Feature.Parent;
            string masterUrl = SPUrlUtility.CombineUrl(siteCollection.ServerRelativeUrl, "_catalogs/masterpage/mysite15.master");

            foreach (SPWeb web in siteCollection.AllWebs)
            {
                try
                {
                    web.MasterUrl = masterUrl;
                    web.CustomMasterUrl = masterUrl;
                    web.Update();
                }
                catch
                {
                    if (web != null)
                        web.Dispose();

                    throw;
                }

                if (web != null)
                    web.Dispose();
            }
        }
    }
}

Step 3 : Stapling the "apply mastepage" feature to the personal site template
This action will hook your feature to any new personal site that will be created after staple is effective. If you need to apply the branding to existing personal write a PowerShell script that activates the feature for each "/my/personal/xxx" :)
NOTE : As the MySiteHost (the "/my" root url) will usually already exist on the customer's target platform when they create their "User Profile Application Service" you'll have to manually activate the "ApplyCustomMasterPage" feature on that site collection (or think PowerShell if needed)



Create a new Feature with scope "Farm" and name it "Farm_MySiteStapler".



Then create a new empty Element name it "ML_ApplyCustomMasterPageStapler".

Add the followin code

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <FeatureSiteTemplateAssociation Id="{ Site_ApplyCustomMasterPage feature ID}" TemplateName="SPSPERS#2" />
</Elements>
Note that in SharePoint 2013 the Template to staple is "SPSPERS#2" whereas in SharePoint 2010 you had to staple "SPSPERS#0".

You will get Feature id in menifest.xml




Add the module to the Stapler feature.

Your projet should look like this:

 At this point the branding will actually work for the root sites, if you wish to apply template to any subsite that will be created (such as Blogs,...) you need to follow step 4 to hook the WebProvisioned event.


Step 4 : Applying the masterpage to any subsite created under the my site


Add a new Event receiver "ER_MySite_ElementsWebProvisioned".


Selected the web event "a site was provisioned".

Then enter the following code:

namespace ClientName.MySitesBranding.Receivers.ER_MySite_ElementsWebProvisioned
{
    using System;
    using Microsoft.SharePoint;

    public class ER_MySite_ElementsWebProvisioned : SPWebEventReceiver
    {
        public override void WebProvisioned(SPWebEventProperties properties)
        {
            SPWeb web = properties.Web;
            SPWeb rootWeb = web.Site.RootWeb;
            web.MasterUrl = rootWeb.MasterUrl;
            web.CustomMasterUrl = rootWeb.CustomMasterUrl;
            web.Update();
        }
    }
}


Now add the Event receiver to the "Site_ApplyCustomMasterPage" feature.

Your project should look like this: 


Deploy your solution, activate the Farm feature and connect with a new user to his MySite check that the new master is applied. 


For already created site, you need to run powershell for activating the feature. :)


Reference :http://sharepointologic.blogspot.in/2013/04/branding-sharepoint-2013-my-sites-with.html

Adding Webpart to webpart pages through powershell

The following powershell will add Custom visual webpart to a webpart page.


if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$Url = "http://sp2013:5559" #Please remove trailing slash if any
$web = Get-SPWeb $Url
$web.AllowUnsafeUpdates=$true

function Add-WebPartToPage($pageUrl, $webpartzone,$index,$fileName)
{
    $webPartGallery = $web.Lists["Web Part Gallery"]
   
    Write-Host "Searching webpart $fileName in web part gallery" -ForegroundColor Yellow
    if($webPartGallery -eq $null)
    {
        Write-Host("Unable to retrieve Webpartgallery");
    }
    $webpart = $null;
    $webpart=$webPartGallery.Items | ? { $_.Title -eq $fileName}

    if($webpart -eq $null) {
        Write-Host("Unable to retrieve webpart: $fileName") -ForegroundColor Red
    }
    else 
{
Write-Host("----------Adding Webpart--------")-ForegroundColor Yellow
$webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$errorMsg = "";
$xmlReader = New-Object System.Xml.XmlTextReader($webpart.File.OpenBinaryStream());
 $webpart = $webpartmanager.ImportWebPart($xmlReader,[ref]"Error")
$webpartmanager.AddWebPart($webpart, $webpartzone, $index);
Write-Host($fileName +" Webpart is added successfully") -ForegroundColor Green ;

   $wp=$webpartmanager.WebParts[1];
    $wp.ChromeType="None";

    $webpartmanager.SaveChanges($wp);

       }
}

$SiteURL =$Url
#---------------Test Page----------------------------
$PageName="TestPage.aspx"
#$page=$web.lists["SitePages"].Items | ? {$_.Name -eq $PageName} 

Add-WebPartToPage "$SiteURL/SitePages/$PageName" "Header" 0 "Test Form"

$PageName="TestPage.aspx"


Powershell for adding Custom list form of a list

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$Url = "http://sp2013:5559" #Please remove trailing slash if any

$listname ="TestList"
$web = get-spweb $Url
$list = $web.lists[$listname]
$files = $list.rootfolder.files






$editformurl = $list.RootFolder.ServerRelativeUrl + "/CustEditForm.aspx"
$dispformurl = $list.RootFolder.ServerRelativeUrl + "/CustDispForm.aspx"
$newformurl = $list.RootFolder.ServerRelativeUrl + "/CustNewForm.aspx"


$dispform = $files.add($dispformurl, [Microsoft.SharePoint.SPTemplateFileType]::FormPage)
$editform = $files.add($editformurl, [Microsoft.SharePoint.SPTemplateFileType]::FormPage)
$newform = $files.add($newformurl, [Microsoft.SharePoint.SPTemplateFileType]::FormPage)

$wpm = $editform.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$wpm2 = $dispform.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$wpm3 = $newform.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$lfw1 = new-object ([Microsoft.SharePoint.WebPartPages.ListFormwebpart])
$lfw2 = new-object ([Microsoft.SharePoint.WebPartPages.ListFormwebpart])
$lfw3 = new-object ([Microsoft.SharePoint.WebPartPages.ListFormwebpart])



$ilist1 = [Microsoft.SharePoint.WebPartPages.IListWebPart]($lfw1)
$ilist2 = [Microsoft.SharePoint.WebPartPages.IListWebPart]($lfw2)
$ilist3 = [Microsoft.SharePoint.WebPartPages.IListWebPart]($lfw3)


$ilist1.ListId = $list.id
$ilist1.PageType = [Microsoft.SharePoint.PAGETYPE]::PAGE_EDITFORM;

$ilist2.ListId = $list.id
$ilist2.PageType = [Microsoft.SharePoint.PAGETYPE]::PAGE_DISPLAYFORM;

$ilist3.ListId = $list.id
$ilist3.PageType = [Microsoft.SharePoint.PAGETYPE]::PAGE_NEWFORM;


$lfw1.Hidden ="True"
$lfw2.Hidden ="True"
$lfw3.Hidden ="True"
$lfw1.ChromeType ="None"
$lfw2.ChromeType ="None"
$lfw3.ChromeType ="None"

$wpm.AddWebPart($lfw1, "Main", 1)
$wpm2.AddWebPart($lfw2, "Main", 1)
$wpm3.AddWebPart($lfw3, "Main", 1)





$list.DefaultDisplayFormUrl = $dispformurl
$list.DefaultEditFormUrl = $editformurl
$list.DefaultNewFormUrl = $newformurl



$list.update()



$SiteURL =$Url
#---------------Test Page----------------------------
$PageName="Rooms/CustNewForm.aspx"
#$page=$web.lists["SitePages"].Items | ? {$_.Name -eq $PageName}
 



$PageName="TestList/CustDispForm.aspx"
#$page=$web.lists["SitePages"].Items | ? {$_.Name -eq $PageName}
 


$PageName="TestList/CustEditForm.aspx"
#$page=$web.lists["SitePages"].Items | ? {$_.Name -eq $PageName}
 

Powershell for Editing Web.config to enable sessionState(inproc)

# Load SharePoint PowerShell PSSnapIn and the main SharePoint .net library
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#set a few variables for the script
$owner = "WebConfigModifications"
$Url = "http://sp2013:5559/"

#Get the web application we want to work with
$webapp = get-spwebapplication $Url
#$webApp.WebConfigModifications | Format-Table Name,Owner
#$webApp.WebConfigModifications.Clear()


#get the Foundation Web Application Service (the one that puts the content web apps on servers)
$farmservices = $webapp.Farm.Services | where { $_.TypeName -eq "Microsoft SharePoint Foundation Web Application" }

 write-host $farmservices


 $newModification = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$newModification.Path = "configuration/system.web/pages"
$newModification.Name = "enableSessionState"
$newModification.Sequence = 0
$newModification.Owner = $owner
$newModification.Type = 1   #for the enum value "SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode"
$newModification.Value = "true"
$webapp.WebConfigModifications.Add($newModification)


$newModification = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$newModification.Path = "configuration/system.webServer/modules"
$newModification.Name ="add[@name='Session']"
$newModification.Sequence = 0
$newModification.Owner = $owner
$newModification.Type =0  #for the enum value "SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode"
$newModification.Value = "<add name='Session' type='System.Web.SessionState.SessionStateModule' />"

#add our web config modification to the stack of mods that are applied
$webapp.WebConfigModifications.Add($newModification)
$webapp.Update()

#trigger the process of rebuildig the web config files on content web applications
$farmServices.ApplyWebConfigModifications()

Powershell for adding webpart pages

#Check and add SharePoint PowerShell snap-in
if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
$web = Get-SPWeb http://hd-spdev02:5559 #Please remove trailing slash if any
$list = $web.GetList("http://hd-spdev02:5559/SitePages/Forms/")
$layoutTemplate = 4  # Template code




function Add-WebPartPage($pageTitle)
{
$xml = "<?xml version=""1.0"" encoding=""UTF-8""?><Method ID=""0,NewWebPage""><SetList Scope=""Request"">" + $list.ID + "</SetList><SetVar Name=""Cmd"">NewWebPage</SetVar><SetVar Name=""ID"">New</SetVar><SetVar Name=""Type"">WebPartPage</SetVar><SetVar Name=""WebPartPageTemplate"">" + $layoutTemplate + "</SetVar><SetVar Name=""Overwrite"">true</SetVar><SetVar Name=""Title"">" + $pageTitle + "</SetVar></Method>"
#$xml = "<?xml version=""1.0"" encoding=""UTF-8""?><Method ID=""0,NewWebPage""><SetList Scope=""Request"">" + $list.ID + "</SetList><SetVar Name=""Cmd"">NewWebPage</SetVar><SetVar Name=""ID"">New</SetVar><SetVar Name=""Type"">WebPartPage</SetVar><SetVar Name=""WebPartPageTemplate"">" + $layoutTemplate + "</SetVar><SetVar Name=""Overwrite"">true</SetVar><SetVar Name=""Title"">" + $pageTitle1 + "</SetVar></Method>"
$result = $web.ProcessBatchData($xml)
}


#Test Form
$pageTitle = "Test"
Add-WebPartPage($pageTitle)



Powershell for uploading documents in Document library

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

#Script settings

$Url = "http://sp2013:5559/"

$docLibraryName = "Documents"
$docLibraryUrlName = "Shared Documents"

$floorLayoutImagesPath = "C:\Images"

#Open web and library

$web = Get-SPWeb $Url

$docLibrary = $web.Lists[$docLibraryName]

$files = ([System.IO.DirectoryInfo] (Get-Item $floorLayoutImagesPath)).GetFiles()

ForEach($file in $files)
{

    #Open file
    try
    {
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

    #Add file
    $folder =  $web.getfolder($docLibraryUrlName)

    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    write-host "Success"

    #Close file stream
    $fileStream.Close();
    }
    catch
    {
 
        continue;
     
    }
}

#Dispose web

$web.Dispose()

Powershell for Installing WSP and activating feature

#Check and add SharePoint PowerShell snap-in
if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

# Function to check if the timer job is complete
function WaitForJobToFinish()
{
    $JobName = "*solution-deployment*$solutionName*"
    $job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
    if ($job -eq $null)
    {
        Write-Output 'Timer job not found'
    }
    else
    {
        $JobFullName = $job.Name
        Write-Output "Waiting to finish job $JobFullName"
       
        while ((Get-SPTimerJob $JobFullName) -ne $null)
        {
            Write-Output .
            Start-Sleep -Seconds 2
        }
        Write-Output  "Finished waiting for job.."
    }
}


$Url="http://sp2013:5959/"

$solutionPath="C:\Users\spadmin\Desktop\"

$solution="Test.wsp"
$path= $solutionPath + $solution
Add-SPSolution -LiteralPath $path
install-spsolution -Identity $solution  -GACDeployment -Force
WaitForJobToFinish

Enable-spfeature -identity "Test_Job" -confirm:$false -url $Url

Powershell for adding Menu item in Global Navigation in sharepoint 2013

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$Url = "http://sp2013:5559/"
$web = Get-SPWeb $Url;
 $CreateNavigationNodeMethod = [Microsoft.SharePoint.Publishing.Navigation.SPNavigationSiteMapNode]::CreateSPNavigationNode      

#Add Test4 link
         $headingNode = $CreateNavigationNodeMethod.Invoke("Test4","/SitePages/Test4.aspx", [Microsoft.SharePoint.Publishing.NodeTypes]::AuthoredLinkPlain, $web.Navigation.TopNavigationBar)
        $headingNode.Properties["Audience"]=";;;;" +"Test1"
     
        $headingNode.Update()

#Add Test3 link

        $headingNode = $CreateNavigationNodeMethod.Invoke("Test3","/SitePages/Test3.aspx", [Microsoft.SharePoint.Publishing.NodeTypes]::AuthoredLinkPlain, $web.Navigation.TopNavigationBar)
        $headingNode.Properties["Audience"]=";;;;" +"Test,Test1"      
        $headingNode.Update()



#Add Dropdown
        $Heading="Test Name Dropdown"
        $CreateNavigationNodeMethod = [Microsoft.SharePoint.Publishing.Navigation.SPNavigationSiteMapNode]::CreateSPNavigationNode      
           
        $headingNode = $CreateNavigationNodeMethod.Invoke($Heading, [System.String]::Empty, [Microsoft.SharePoint.Publishing.NodeTypes]::Heading, $web.Navigation.TopNavigationBar)
       
        $headingCollection = $headingNode.Children  
       
     

            $linkNode = $CreateNavigationNodeMethod.Invoke("Test Dropdown", "/_layouts/ApplicationPages/Test.aspx", [Microsoft.SharePoint.Publishing.NodeTypes]::AuthoredLinkPlain,$headingCollection)
            $linkNode.Properties["Audience"]=";;;;" +"Test2,Test3"
            $linkNode.Update()

         
     

       

       
         
           

Powershell for Adding Content Editor Webpart to a List Form in Sharpeoint 2010 & 2013

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$Url = "http://sp2013:5959" #Please remove trailing slash if any
$web = Get-SPWeb $Url
$web.AllowUnsafeUpdates=$true

#setting modal Dialog for all List Forms
foreach ($list in $web.Lists)
{
    $list.NavigateForFormsPages = $false;              
    $list.Update();
}


function Add-WebPartToPage($pageUrl, $webpartzone,$index,$fileName)
{
 
Write-Host("----------Adding Content Editor Webpart--------" +$filename)-ForegroundColor Yellow
$webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$errorMsg = "";
$lvwpGuid1 = [System.Guid]::NewGuid().ToString()
$lvwpKey = "g_" + $lvwpGuid1.Replace("-","_")
 
# Instantiate wp
$lvwp =New-Object Microsoft.SharePoint.WebPartPages.ContentEditorWebPart  
$lvwp.ID = $lvwpKey
$code = "$"
$lvwp.ContentLink = "/Style%20Library/TestFolder/Dialog.css"
$lvwp.Title = "Content Editor"  
$lvwp.Hidden ="True"  
$lvwp.ChromeType = "None"
$lvwp.HorizontalAlign = "Center"  
 
# Add the web part
$webpartmanager.AddWebPart($lvwp, "Main", 0);
 
$web.Update();


     
}


$SiteURL =$Url
#---------------Test Lists----------------------------
$PageName="Test/NewForm.aspx"
Add-WebPartToPage "$SiteURL/Lists/$PageName" "Header" 0 "Content Editor"

$PageName="Test/DispForm.aspx"
Add-WebPartToPage "$SiteURL/Lists/$PageName" "Header" 0 "Content Editor"

$PageName="Test/EditForm.aspx"
Add-WebPartToPage "$SiteURL/Lists/$PageName" "Header" 0 "Content Editor"


Thursday, 6 March 2014

PowerShell Script To Upload Data From Local Drive To SharePoint Document Library

Below Script uploads all The Document from Your Local Drive Folder To SharePoint Document Library with error log file


if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

#Script settings

$webUrl = "http://xyz:4444/"

$docLibraryName = "Documents"
$docLibraryUrlName = "Shared Documents\Test"

$localFolderPath = "C:\\Test\\Test"

#Open web and library

$web = Get-SPWeb $webUrl

$docLibrary = $web.Lists[$docLibraryName]

$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()

ForEach($file in $files)
{

    #Open file
    try
    {
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

    #Add file
    $folder =  $web.getfolder($docLibraryUrlName)

    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
    write-host "Success"

    #Close file stream
    $fileStream.Close();
    }
    catch
    {
    Write "Error: $file.name: $_" >>c:\logfile.txt
        continue;
    }
}

#Dispose web

$web.Dispose()

 

PowerShell Script To download Bulk data from Document Library in SharePoint

Below Script Downloads All The Documents With all Sub folders of Document library. It also downloads CSV file which contains Metadata information of Downloaded documents. Also Catch block will Generate Error Log File .


if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$destination = "C:\\Test\\"
$web = Get-SPWeb -Identity "http://xyz:4444/"
$list = $web.GetList("http://xyz:4444/Shared Documents/")

function ProcessFolder {
    param($folderUrl)
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files) {
        #Ensure destination directory
        $destinationfolder = $destination + "/" + $folder.Url
        if (!(Test-Path -path $destinationfolder))
        {
            $dest = New-Item $destinationfolder -type directory
        }
        #Download file
        try
        {
      
        $binary = $file.OpenBinary()
        $stream = New-Object System.IO.FileStream($destinationfolder + "/" + $file.Name), Create
        $writer = New-Object System.IO.BinaryWriter($stream)
        $writer.write($binary)
        $writer.Close()
         }
        catch
        {
        Write "Error: $file.name: $_" >>c:\logfile.txt
        continue;
        }
     
        }
}
$exportlist = @()
$list.Items | foreach {
$obj = New-Object PSObject -Property @{
"Title" = $_["Title"]
"Name" = $_["Name"]
"Modified Date" = $_["Modified"]
"Modified By" =$_["Modified By"]
"Size"= $_["File Size"]
"Path" = $web.Url + "/" + $_.File.Url
}
$exportlist += $obj
$exportlist | Export-Csv -path 'C:\Test\MyList.csv' -noType
}

#Download root files
ProcessFolder($list.RootFolder.Url)
#Download files in folders
foreach ($folder in $list.Folders) {
    ProcessFolder($folder.Url)
   
}

Wednesday, 5 March 2014

SharePoint 2010 To SharePoint 2013 Step By Step Ugrade process


SharePoint 2010 to SharePoint 2013 Upgrade Step By step


Step1:

1.Backup Content Database of SharePoint 2010 from Sql Server Management 2008 R2

            1.Open Sql Server Management 2008 R2

            2.Right Click on your Content Database

            3.Task

            4.backup(Save as DatabaseName.Bak)

2.convert all your WSP solutions in 2013 from 2010

a.Open Visual Studio 2012

b.Edit yours .csproj file and add to it -> <TargetOfficeVersion>15.0</TargetOfficeVersion>

c.Reload the project again

d.In webpart.cs file,change the path of user control for eg :

private const string _ascxPath = @"~/_CONTROLTEMPLATES/15/SolutionName/Webpart/WebpartUserControl.ascx";

e.open WebpartUserControl.ascx source code and change all 14.0.0 references to 15.0.0
f.Double Click on Packages and change the Product Version to 15.

g. Right Click On your Project and Choose Properties. in Application Tab Choose Target FrameWork as 4.5
h. Click On build tab and Choose Platform Target As x64.
g. Publish it and save WSP (Example.WSP) on Your Storage Location.

 3.now Install That WSP in SharePoint 2013 Farm using Add-SPSolution "c:\Example.WSP" in Powershell ISE 64 Bit

4.Deploy all the custom WSP's on Your Web Application

Step 2:

1.Create New Web Application in SharePoint 2013(Don't create Site Collections)

Step 3:

Restore Your Database(DatabaseName.Bak)
a. Go To Sql Server Management 2012

b. Right Click On Database on top

c.Restore

d. Select your DatabaseName.Bak from Disk and start Restoring

Go to Powershell and Type

Test-SPContentDatabase -Name WSS_Content_DataBName -WebApplication http://WebApplName:90


(Change WSS_Content_DataBName with You DataBase Name and http://WebApplName:90 with Your WebApplication Name)

This will Test your database with webApplication.It will throw Warnings like Your New Web Application is claim Based etc

Note: By default 2013 is claim based and SharePoint 2010 is Classic Windows Authentication.

You can convert your New Web Application to Classic Windows Authentication using Powershell



Step 4:

Use Powershell ISE 64 bit or SharePoint 2013 Management Shell and type the following as it is

cd "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN\"


Then Type the following

stsadm .exe-o addcontentdb -url http://WebApplName:90 -databasename WSS_Content_DataBName



OR


Run the below powershell command

Mount-SPContentDatabase "WSS_Content_DataBName" -DatabaseServer "SQLSERVER2012" -WebApplication http://testSite


If everything is fine, Operation will Complete Successfully Otherwise it will throw some errors.





Step 5:

Open your new Web Application In browser if Operation Completes Successfully.

Your Web Application Will Look Similar to the SharePoint 2010 .

Click On start Now button On Top in Red and follow The steps.

 Refresh it Several Times and Your web Application will get Ready if It doesn't throw Any error.

If there are any errors, rectify those and follow the start process again in web browser.



 Step 6: Migrate all users from classic to claims using below powershell



 if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$WebAppName = "https://TestSite/"

$wa = get-SPWebApplication $WebAppName

#Final step is to trigger the user migration process
$wa = get-SPWebApplication $WebAppName
$wa.MigrateUsers($true)