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
}