Monday, February 23, 2015

Powershell suit for all functionalities - SharePoint 2010/2013

Hey Folks,

I was thought to share one of my idea to share most of the common powershell commands we were using daily in our day to day jobs, in SharePoint. I'm sure this should be helpful to you in your needs. Code is not debugged fully. So go for it.


Add-PSSnapin Microsoft.SharePoint.Powershell -EA 0

Write-host -ForegroundColor Yellow 'Powershell suit for SharePoint 2010/2013 Manipulation!'

Write-host '---------------------------------------------------------'
Write-host ''
Write-host 'This suit will facilitate most of the common tasks that will perform by SharePoint developer.'


Write-host 'Please enter your option to proceed......'
Write-host ''
Write-host -ForegroundColor Green '########## Bulk Operations'
Write-host ''
Write-host 'Create bulk number of items to custom list - Enter 1'
Write-host 'Delete bulk number of items from custom list - Enter 2'
Write-host 'Get Item Count of a list - Enter 3'
Write-host ''
Write-host -ForegroundColor Green '########## General Site level operations'
Write-host ''
Write-host 'Get Content Types and their GUIDs - Enter 4'
Write-host 'Get custom web templates deployed - Enter 5'
Write-host 'Get site/web level features - Enter 6'
Write-host 'Activate/Deactivate specific feature on specific Scope - Enter 7'
Write-host 'Get the WSPs deployed in solution store - Enter WSPS'
Write-host 'Add, Deploy WSP and Activate features in a site collection - Enter DEP'
Write-Host 'Upgrade WSP - Enter UPG'
Write-host 'Retract particular wsp and remove - Enter REM'
Write-host ''
Write-host -ForegroundColor Green '########## Powershell general informations'
Write-host ''
Write-host 'Get the powershell version of the environment - VER'
Write-host ''

$answer = Read-Host 'Please enter your option '
Write-host ''


switch($answer)
{
 # Creating bulk number of items
 1 {
  Write-host -ForegroundColor Green 'Your answer is : 1'
  Write-host ''
  $siteUrl = Read-Host 'Please enter site url '
  $listName = Read-Host 'Please enter List Name to get Item Count '
  Write-host ''
  $webUrl = $siteUrl
  $listName = $listName
  $numberItemsToCreate = 20000
  $itemNamePrefix = "Title "
   
  # Open web and library
  $web = Get-SPWeb $webUrl
  $list = $web.Lists[$listName]
   
  # Create desired number of items in subfolder
  for($i=1; $i -le $numberItemsToCreate; $i++)
  {
   $newItemSuffix = $i.ToString("000000")
   $newItem = $list.AddItem()
   # List item fields need to be populate here.
   $newItem["Title"] = "$itemNamePrefix$newItemSuffix"
   $newItem.Update()
   write-host "Item created: $itemNamePrefix$newItemSuffix"
  }

  #Dispose web
  $web.Dispose()
 }
 # Deleting bulk number of items
 2 {
  Write-host -ForegroundColor Green 'Your answer is : 2'
  Write-host ''
  Write-host -ForegroundColor Green 'Batch process will delete items in batches of 2000 >>>'
  Write-host ''
  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
  $siteUrl = Read-Host 'Please enter site url '
  $listName = Read-Host 'Please enter List Name to get Item Count '
    $site = new-object Microsoft.SharePoint.SPSite($siteUrl)
    Write-Host "SiteURL", $siteUrl

    $sw = New-Object System.Diagnostics.StopWatch
    $sw.Start()

    $web = $site.OpenWeb()   
    $myList = $web.Lists[$listName]
    Write-Host "Items Number before delete: ", $myList.Items.Count

  $guid = $myList.ID
  $strGuid = $guid.ToString()

    $strPost = "<?xml version=""1.0"" encoding=""UTF-8""?><ows:Batch OnError='Return'>"
    foreach($item in $myList.Items)
    {
    $strPost += "<Method><SetList Scope=""Request"">"+ $strGuid +"</SetList>"
    $strPost += "<SetVar Name=""ID"">"+ $item.ID +"</SetVar><SetVar Name=""Cmd"">Delete</SetVar>"
    $strPost += "</Method>"
    }
    $strPost += "</ows:Batch>"

  # Write-Host "Batch: " $strPost
    $strProcessBatch = $web.ProcessBatchData($strPost)
    
    Write-Host "Result: " $strProcessBatch 

    $sw.Stop()
    Write-Host "Items total after delete: ", $myList.Items.Count
    #write-host "$y Items add in " $sw.Elapsed.ToString()
    
    $web.Dispose()
    $site.Dispose()
 }
 # Count the items in a custom list
 3 {
  Write-host -ForegroundColor Green 'Your answer is : 3'
  Write-host ''
  $siteUrl = Read-Host 'Please enter site url '
  $listName = Read-Host 'Please enter List Name to get Item Count '
  
  $site = new-object Microsoft.SharePoint.SPSite($siteUrl)
    

  $sw = New-Object System.Diagnostics.StopWatch
  $sw.Start()

  $web = $site.OpenWeb()   
  $myList = $web.Lists[$listName]
  Write-Host "Number of Items in the list: ", $myList.Items.Count
 }
 # Get Content Types and their GUIDs
 4 {
  Write-host -ForegroundColor Green 'Your answer is : 3'
  Write-host ''
  $siteUrl = Read-Host 'Please enter site url '
   
  $site = new-object Microsoft.SharePoint.SPSite($siteUrl)
  $cts = $site.rootweb.ContentTypes
 

  '"CT Name"' + `
  ',"CT ID"' `
  #',"CT Description"' + `
  #',"CT Group"' +
  #',"Field Title"' + `
  #',"Field Internal Name"' + `
  #',"Field ID"' + `
  #',"Field Group"' + `
  #',"Field Max Length"' + `
  #',"Field Description"' 

  ForEach ($id in $cts)
  {
   '"' + $id.Name + `
   '","' + $id.Id + `
   '"' 
    
    #ForEach ($field in $id.Fields)
    #{
   #'"' + $id.Name + `
   #'","' + $id.Id + `
   #'","' + $id.Description + `
   #'","' + $id.Group + `
   #'","' + $field.Title + `
   #'","' + $field.InternalName + `
   #'","' + $field.Id + `
   #'","' + $field.Group + `
   #'","' + $field.MaxLength + `
   #'","' + $field.Description + `
   #'"' 
    #}
  }

  $site.Dispose()
 }
 # Get custom web templates deployed
 5 {

  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  $web = Get-SPweb $siteUrl 
  Write-host "Web Template:" $web.WebTemplate " | Web Template ID:" $web.WebTemplateId 
  $web.Dispose()

  # To get a list of all web templates, use the following PowerShell code

  function Get-SPWebTemplateWithId 
  { 
    $templates = Get-SPWebTemplate | Sort-Object "Name" 
    $templates | ForEach-Object { 
   $templateValues = @{ 
    "Title" = $_.Title 
    "Name" = $_.Name 
    "ID" = $_.ID 
    "Custom" = $_.Custom 
    "LocaleId" = $_.LocaleId 
     }

  New-Object PSObject -Property $templateValues | Select @("Name","Title","LocaleId","Custom","ID") 
     } 
  }

  Get-SPWebTemplateWithId | Format-Table


 }
 # Get site level features
 6 {

  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
 
  #Get-SPFeature | Sort -Property DisplayName
 
  #Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id
 
  Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id
 
  #Get-SPFeature -Site $siteUrl | Sort DisplayName | FT DisplayName,Id
 
  #Get-SPSite $siteUrl | Get-SPWeb -Limit ALL | %{ Get-SPFeature -Web $_ } | Sort DisplayName -Unique | FT DisplayName,Id

 }
 # Activate/Deactivate feature on a specific site collection
 7 {
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  $FeaturefolderName = Read-Host "Enter Feature folder name ";
  $SiteScope = Read-Host "Enter site scope ";
  
 
  function Check-SPFeatureActivated
  {
  #Write-Host "inside function";
   param([string]$FeaturefolderName=$(throw "-FolderName parameter is required!"),
     [Microsoft.SharePoint.SPFeatureScope]$Scope=$(throw "-Scope parameter is required!"),
     [string]$Url)  
   if($Scope -ne "Farm" -and [string]::IsNullOrEmpty($Url))
   {
    throw "-Url parameter is required for scopes WebApplication,Site and Web"
   }
   $feature=$null
     
    switch($Scope)
    {
     #"Farm" { $feature=Get-SPFeature $FeaturefolderName -Farm }
     #"WebApplication" { $feature=Get-SPFeature $FeaturefolderName -WebApplication $Url }
     #"Site" { $feature=Get-SPFeature $FeaturefolderName -Site $Url }
     #"Web" { $feature=Get-SPFeature $FeaturefolderName -Web $Url }
    
     Site {
       try
       {
        $feature=Get-SPFeature $FeaturefolderName -Site $Url
       }
       catch [System.Management.Automation.ActionPreferenceStopException]
       {
        if( !($_.Exception -is [System.Data.DuplicateNameException]) )
        {
         #Its not a "feature is already activated at scope" exception
         #throw 
         Write-Host -ForegroundColor Yellow "Feature already activated!"
         $feature = False;
        }
       
       }    
     }
     Web {
    
       try
       {
        $feature=Get-SPFeature $FeaturefolderName -Web $Url
       }
       catch [System.Management.Automation.ActionPreferenceStopException]
       {
        if( !($_.Exception -is [System.Data.DuplicateNameException]) )
        {
         #Its not a "feature is already activated at scope" exception
         #throw 
         Write-Host -ForegroundColor Yellow "Feature already activated!"
         $feature = False;
        }
       
       }
      
    
     }
    
    }
   #}
  
  
   #return if feature found or not (activated at scope) in the pipeline
   $feature -ne $null
  }

  $IsAlreadyDeployed = Check-SPFeatureActivated -FeaturefolderName $FeaturefolderName -Scope $SiteScope -Url $siteUrl
 
  if($IsAlreadyDeployed)
  {
   Write-Host -foregroundcolor Red "Feature already activated!"
   Write-Host " "
   Write-Host -foregroundcolor yellow "Deactivating the feature!"
   Write-Host " "
   Disable-SPFeature $FeaturefolderName -Url $siteUrl
   Write-Host " "
   #Write-Host "Enabling the feature!"
   #Write-Host " "
   #Enable-SPFeature $FeaturefolderName -Url $siteUrl
   
  }
  else
  {
      Write-Host -foregroundcolor Green "Enabling the feature in site level!"
   Write-Host " "
  
   Enable-SPFeature $FeaturefolderName -Url $siteUrl
  
  }
 
  #Enable-SPFeature $FeaturefolderName -Url $siteUrl
 
  

 }
 # Get the powershell version
 VER {
  Write-host 'Your powershell Version is :'
  Write-host ''
  $PSVersionTable.PSVersion
 }
 # Get the WSP deployed
 WSPS {
  [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
  $farm=[Microsoft.SharePoint.Administration.SPFarm]::Local
  Write-Host -foregroundcolor Yellow "WSP's deployed to the solution store!"
  Write-Host " "
  Write-Host "==============================================================="
  Write-Host " "
  foreach ($solution in $farm.Solutions) 
    {
     if ($solution.Deployed){
        Write-Host $solution.DisplayName " | " $solution.Status   #need to check the statuses provide by this $solution variable            
     }          
    }
  Write-Host " "
 }
 # Add, Deploy WSP and Activate features in a site collection
 DEP {
  # read wsp package location
  $fileUrl = Read-Host "Enter Location to the WSP ";
  #$fileUrl = "< location>"
 
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  #$siteUrl = "<url>";
 
  # Get WSP name
  $fileName = Read-Host "Enter WSP Name ";
  #$fileName = "TestWspDeployment.wsp";
 
  $file = $fileUrl + $fileName;
  # Add WSP to solution store
 
 
  Add-SPSolution -LiteralPath $file;
  $sln = get-spsolution -identity $fileName;
   Install-SPSolution -Identity $fileName -WebApplication $siteUrl -GACDeployment -Force;
   while($sln.JobExists) { 
   Write-Host -NoNewLine .
   start-sleep -s 2 
   };
   Write-Host " "
   Write-Host " "
   Write-Host -ForegroundColor Yellow "Solution $fileName Deployed successfully!"
 }
 # Upgrade selected WSP
 UPG {

  # read wsp package location
  #$fileUrl = Read-Host "Enter Location to the WSP ";
  #$path = "<location>"
 
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  #$siteUrl = "<url>";
 
  # Get WSP name
  $file = Read-Host "Enter WSP Name ";
  #$file = "TestWspDeployment.wsp";
 
  #$file = $fileUrl + $fileName;
  # Add WSP to solution store
 

  # Get the path to WSP
  $path = Read-Host "Enter Location to the WSP ";
  # Get the WSP Name
  #$file = Read-Host "Enter WSP Name ";
  # Get site collection
  #$siteUrl = Read-Host "Enter Site Collection URL ";

  Write-Host "Upgrading solution:" $file -ForegroundColor Green
  Update-SPSolution -Identity $file -LiteralPath $path$file -GACDeployment
  $solution = Get-SPSolution $file
  Write-Host "Waiting for solution upgrade to complete" -ForegroundColor Green

  while ($solution.JobExists -eq $true) {
   Write-Host "." -NoNewline
   sleep 1
   $solution = Get-SPSolution $file
  }
  ""
  Write-Host "Solution upgrade completed " $file -ForegroundColor Green

  Write-Host "Restarting IIS Services."

  IISRESET /NOFORCE


 }
 # Retract and Remove WSP after deactivating features
 REM {
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  #$siteUrl = "<url>";
 
  # Get the WSP Name
  $file = Read-Host "Enter WSP Name ";
  #$file = "TestWspDeployment.wsp";
 
 
  # Check if solution exists.
  $Solution = Get-SPSolution | ? {($_.Name -eq $file) -and ($_.Deployed -eq $true)}  -ErrorAction SilentlyContinue
  if ($Solution -ne $null)   
  {

   Write-Host "Retracting solution: $file" 
   if($Solution.ContainsWebApplicationResource)   
   {   
    Uninstall-SPSolution $file -AllWebApplications -Confirm:$false   
   }   
   else   
   {   
    Uninstall-SPSolution $file -Confirm:$false   
   }
   # There is a error in this line Restart-SPAdminV4
   #Restart-SPAdminV4
   while ($Solution.JobExists)
   {
    Write-Host -NoNewLine .
    Start-Sleep 2
   }
   Write-Host ""
   Write-Host "$file retracted successfully."  -foregroundcolor Green
   Write-Host ""
   if ($(Get-SPSolution | ? {$_.Name -eq $file}).Deployed -eq $false)
   {
   Write-Host ""
    Write-Host "Removing solution: $file" 
    Write-Host ""
    Remove-SPSolution $file -Confirm:$false
    Write-Host "$file removed successfully from solution store!"  -foregroundcolor Green
    Write-Host ""
   }
  } 
  else
  {
 
  $Solution2 = Get-SPSolution | ? {($_.Name -eq $file) -and ($_.Deployed -ne $true)}  -ErrorAction SilentlyContinue
   if($Solution2 -ne $null)
   {
   Write-Host "Solution not deployed!"
   $GetAnswer = Read-Host "Remove solution from solution store (Y/N) "
    if($GetAnswer = "Y")
    {
     Write-Host ""
     Write-Host "Removing solution: $file" 
     Write-Host ""
     Remove-SPSolution $file -Confirm:$false
     Write-Host "$file removed successfully."  -foregroundcolor Green
     Write-Host ""
    }
   }
  }
 

 }

 Default {}

}

function Restart-SPAdminV4
{
    Stop-Service SPAdminV4
    Start-SPAdminJob 
    Start-Service SPAdminV4
}






Tuesday, October 21, 2014

Check Workflow association of list items

Hi,

I was researching on this matter and found a way implement. I got event handler for my submit button and I have added my code inside it.

In my test, I'll be getting site collection url from a textbox and evaluate all the webs inside that site collection. We will go inside web object and get all the lists and evaluate whether any item associated with a workflow that running status as 2, which is "In progress". Code is below

            string SiteUrl = string.Empty;
            ArrayList inflightWorkflowDocuments = new ArrayList();
 
            if (string.IsNullOrEmpty(txtSiteUrl.Text.ToString()))
            {
                throw new Exception("Site URL is empty!");
            }
            else
            {
                SiteUrl = txtSiteUrl.Text.ToString();
            }
 
            //Check site collection exist or not
 
            bool isSteExist = SPSite.Exists(new Uri(SiteUrl));
 
            if (isSteExist && !string.IsNullOrEmpty(SiteUrl))
            {
                using (SPSite site = new SPSite(SiteUrl))
                {
                    //Loop through all webs
                    SPWebCollection allWebs = site.AllWebs;
                    Dictionary<stringstring> liUrls = new Dictionary<stringstring>();
 
                    foreach (SPWeb theWeb in allWebs)
                    {
                        Guid webGuid = theWeb.ID;
                        using (SPWeb web = allWebs[webGuid])
                        {
                            SPListCollection cusLists = null;
                            if (null != web.Lists)
                            {
                                //Get list of lists (custom/OOB lists)
                                cusLists = web.Lists;
                            }
 
                            if (null != cusLists)
                            {
                                foreach (SPList sltList in cusLists)
                                {
                                    if (sltList.Title == "TestList")
                                    {
                                        //Get each list and iterate through all items on that list
                                        foreach (SPListItem litem in sltList.Items)
                                        {
 
                                            //Check all workflows and their associations
                                            int wkflStatus = GetWorkflowStatus(litem);
 
                                            /*   Workflow statuses
                                     
                                                    Not Started                     0
                                                    Failed on Start                 1
                                                    In Progress                     2
                                                    Error Occurred                  3
                                                    Canceled                        4
                                                    Completed                     5
                                                    Failed on Start (retrying)     6
                                                    Error Occurred (retrying)     7
                                                    Canceled                     15
                                                    Approved                     16
                                                    Rejected                     17
                                                */
 
                                            //Check that list item having Workflow 'In Progress'
                                            if (wkflStatus == 2)
                                            {
                                                //Rest of your work                                               
                                            }
                                        }
 
                                    }
                                    
                                }
                            }
                        }
                    }
                }
            }
 
            
            //Creating a grid view with items having workflow associated.
 
            if (null != inflightWorkflowDocuments)
            {
                grdWorkflowItems.DataSource = (string[])inflightWorkflowDocuments.ToArray(typeof(string));
                grdWorkflowItems.DataBind();            
            }
}


public int GetWorkflowStatus(SPListItem item)
        {
            if (item == null)
                return -1;
 
            SPWorkflowManager manager = item.Web.Site.WorkflowManager;
            foreach (SPWorkflow instance in manager.GetItemWorkflows(item))
            {
                if ((instance != null) && (instance.ParentList != null) && (instance.ParentList.Fields != null))
                {
                    foreach (SPField field in instance.ParentList.Fields)
                    {
                        if ((field != null) && (field is SPFieldWorkflowStatus))
                        {
                            SPFieldWorkflowStatus statusField = (SPFieldWorkflowStatus)field;
                            if (item[statusField.StaticName] != null)
                            {
                                int statusValue = -1;
                                try
                                {
                                    statusValue = int.Parse(item[statusField.StaticName].ToString());
                                }
                                catch { }
                                return statusValue;
                            }
                        }
                    }
                }
            }
            return -1;
        }

Wednesday, September 24, 2014

Memory gates checking failed because the free memory is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Hi Friends,

Did you ever experienced below error while loading newly created Team Site on SharePoint 2013? 




Root cause: This is happening because of excess memory using by the SharePoint 2013.

I think there are 2 solutions. Just find below service and restart it. 

Solution 1



It will release some memory leaks on host controller. then refresh the browser to load the page.

Solution 2

1.Open IIS by running CTRL+R -> inetmgr
2.Identify the WebService that calling by the web page



3.Right Click -> Explore
4.Edit Web.config file
5.Modify node serviceHostingEnvironment

<serviceHostingEnvironment minFreeMemoryPercentageToActivateService="1" />


6.Just save web.config and do a IISRESET

double check your environment.

References:

http://stevemannspath.blogspot.com/2012/07/sharepoint-2013-opening-memory-gates.html
http://kancharla-sharepoint.blogspot.com/2013/04/sharepoint-memory-gates-checking-failed.html

That's it. Good Luck!