Saturday, October 31, 2015

Copy SharePoint Alerts from One User to Another using PowerShell

Requirement: Copy SharePoint Alerts from one user to Another.

PowerShell script to copy SharePoint Alerts from one user to another:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

Function Copy-SPAlerts($SiteURL, $SourceUserAccount, $TargetUserAccount)
{
 #Get the Site
 $Site = Get-SPSite $SiteURL

 #Iterate through each web
 foreach($web in $site.AllWebs)
 {
  #Resolve users
  $SourceUser=$web.EnsureUser($SourceUserAccount)
  $TargetUser = $web.EnsureUser($TargetUserAccount)
  
  #Get all alerts from the source user
  $SourceAlertCollection=$SourceUser.Alerts
  
  #loop through each alert of the source user and copy it to target suer
  foreach($SourceAlert in $SourceAlertCollection)
  {
   Write-host "Copying Alert from: $($Web.Url)/$($SourceAlert.ListUrl)"
  
   #Copy alerts from source user to destination
         $NewAlert = $TargetUser.Alerts.Add()
         $NewAlert.Title = $SourceAlert.Title
         $NewAlert.AlertType = $SourceAlert.AlertType
         $NewAlert.User = $TargetUser
         $NewAlert.List = $SourceAlert.List
         $NewAlert.DeliveryChannels = $SourceAlert.DeliveryChannels
         $NewAlert.EventType =  $SourceAlert.EventType
         $NewAlert.AlertFrequency = $SourceAlert.AlertFrequency
         $NewAlert.Update()
  }
 }
}

#Configuration variables
$SiteURL="http://portal.crescent.com"
$SourceUserAccount="Crescent\Jitin"
$TargetUserAccount ="Crescent\Nassim"

#Call the function to copy alerts
Copy-SPAlerts $SiteURL $SourceUserAccount $TargetUserAccount 


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


How to Stop and Start All SharePoint 2013 Farm Services using PowerShell

Prior to SharePoint patching, its a best practice to Stop all SharePoint 2013 and its related services and then start once patching is completed. If you don't do this, your service pack or patch installation will take longer than its expected.

So what are all the services to be stopped?
  • SharePoint 2013 Search Service (OSearch15 - OSearch16 in SharePoint 2016)
  • SharePoint 2013 Timer Job (SPTimerV4)
  • SharePoint 2013 Administration (SPAdminV4)
  • SharePoint 2013 Tracing (SPTraceV4)
  • SharePoint 2013 VSS Writer (SPWriterV4)
  • SharePoint 2013 User Code Host (SPUserCodeV4)
  • SharePoint Search Host Controller (SPSearchHostController)
  • Forefront Sync Service (FIMSynchronizationService)
  • Forefront Service (FIMService)
  • World Wide Web Publishing Service (W3SVC)
  • Internet Information Services (IIS)
How to Stop and Start SharePoint 2013 Farm using PowerShell
Don't forget to do it in all your SharePoint Servers of the farm!

Stop all SharePoint 2013 Services
Lets use PowerShell to stop and start all SharePoint services:
Add-PSSnapin Microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$SharePointServices = ('SPSearchHostController','OSearch15','SPWriterV4','SPUserCodeV4','SPTraceV4','SPTimerV4','SPAdminV4','FIMSynchronizationService','FIMService','W3SVC')

#Stop all SharePoint Services
foreach ($Service in $SharePointServices)
{
    Write-Host -ForegroundColor red "Stopping $Service..."
    Stop-Service -Name $Service
}

#Stop IIS
iisreset /stop

Start all SharePoint 2013 Services:
After the patching, Use the below script to start all SharePoint services.
Add-PSSnapin Microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$SharePointServices = ('SPSearchHostController','OSearch15','SPWriterV4','SPUserCodeV4','SPTraceV4','SPTimerV4','SPAdminV4','FIMSynchronizationService','FIMService','W3SVC')

#Start all SharePoint Services
foreach ($Service in $SharePointServices)
{
    Write-Host -ForegroundColor green "Starting $Service..."
    Start-Service -Name $Service
}

#Start IIS
iisreset /start
You may need this script when you want to do some maintenance activity on your SharePoint SQL databases and needed to stop all SharePoint connections! Please note, based on the server roles, You may have to stop distributed cache services: DCLoadBalancer15 , DCLauncher15.

Completely Stop or Start SharePoint Farm Services on All Servers:
Lets put everything together and make a reusable PowerShell function, which stops or starts all SharePoint related services in all servers of the farm.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function StartOrStop-SPFarm()
{
    Param(
    [parameter(Mandatory=$true)] $StartOrStopOption
    )

    #Get All Servers in the Farm 
    $Farm = Get-SPFarm
    $Servers = $Farm.Servers | Where-Object {$_.Role -ne [Microsoft.SharePoint.Administration.SPServerRole]::Invalid} 
    Write-Host "Total Number of Servers in the Farm: " $Servers.Count 

    #List of All SharePoint Services
    $SharePointServices = ('SPSearchHostController','OSearch15','SPWriterV4','SPUserCodeV4','SPTraceV4','SPTimerV4','SPAdminV4','FIMSynchronizationService','FIMService','W3SVC','DCLoadBalancer15', 'DCLauncher15')

    #Iterate through each server
    $Servers | ForEach-Object {
     Write-Host "Performing Operation on Server:" $_.Name
       
        #Loop through each service
     foreach($ServiceName in $SharePointServices)
     {
      $ServiceInstance = Get-Service -ComputerName $_.Name -Name $ServiceName -ErrorAction SilentlyContinue
      if($ServiceInstance -ne $null)
      {
                If($StartOrStopOption -eq "Stop")
                {
        Try 
                    {
                        Write-Host "Attempting to stop service" $ServiceName ".." -ForegroundColor Yellow
         Stop-Service -InputObject $ServiceInstance
         Write-Host "Stopped Service" $ServiceName -ForegroundColor Green 
                    }

        catch 
                    {
         Write-Host "Error Occured on Stopping Service. " $_.Message  -ForegroundColor Red 
                    }
                }
                elseif ($StartOrStopOption -eq "Start")
                {
                    Try 
                    {
                        Write-Host "Attempting to start service" $ServiceName ".." -ForegroundColor Yellow
         Start-Service -InputObject $ServiceInstance
         Write-Host "Started Service" $ServiceName -ForegroundColor Green 
                    }

        catch 
                    {
         Write-Host "Error Occured on Starting Service. " $_.Message  -ForegroundColor Red 
                    }   
                }
      }
     }
        #Start of Stop IIS
        If($StartOrStopOption -eq "Stop") { iisreset /stop} elseif ($StartOrStopOption -eq "Start") {iisreset /start}
    }
}

#Call the function to Stop or Start Services
StartOrStop-SPFarm -StartOrStopOption "Stop"
#StartOrStop-SPFarm -StartOrStopOption "Start"


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


SharePoint 2013 Search Crawl Log History Report

Requirement: Generate SharePoint 2013 search crawl report on daily basis.

Solution: Crawl history can be viewed from SharePoint 2013 search service application as in the below screen. It gives the crawl log history report for all content sources.
sharepoint 2013 crawl history
Why don't we automate it with PowerShell, so that we'll get crawl history report in E-mail?

PowerShell to get crawl log history in E-mail:
This PowerShell script extracts crawl history data and sends out Email.
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#Get the search service application
$SSA = Get-SPEnterpriseSearchServiceApplication #-Identity "Search Service Application Name"

#Get all content sources
$ContentSources = Get-SPEnterpriseSearchCrawlContentSource -SearchApplication $SSA #| where {$_.Name -eq $ContentSourceName}

$ReportDate = Get-Date -format "dd-MM-yyyy"

#CSS Styles for the Table
$style = "Crawl History Report: "
$style = $style + "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; }"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 2px; }"
$style = $style + "</style>"


#Frame Email body
$EmailBody = $ContentSources | Select Name, SuccessCount, WarningCount, ErrorCount,CrawlStarted,CrawlCompleted,  @{label="CrawlDuration";expression={$_.CrawlCompleted - $_.CrawlStarted}} | ConvertTo-Html -Head $style 

#Set Email configurations

#Get outgoing Email Server
$EmailServer = (Get-SPWebApplication -IncludeCentralAdministration | Where { $_.IsAdministrationWebApplication } ) | %{$_.outboundmailserviceinstance.server} | Select Address

$From = "CrawlReport@crescent.com"
$To = "SharePointAdmin@crescent.com"
$Subject = "Crawl History Report as on: "+$ReportDate
$Body = "Hi SharePoint Team,<br /><br />Here is a Crawl History report as on $ReportDate <br /><br />" + $EmailBody

#Send Email
Send-MailMessage -smtpserver $EmailServer.Address -from $from -to $to -subject $subject -body $body -BodyAsHtml
Schedule the above script in Windows task scheduler to receive E-mail notifications on schedule basis. Here is the script in action:
sharepoint 2013 search crawl history


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


Friday, October 23, 2015

Delete All List Items in SharePoint Online using PowerShell

Requirement: SharePoint Online PowerShell to Delete List items
We've a list in SharePoint online - Office 365 site. with bunch of items. Need them to be deleted in bulk rather deleting one by one from SharePoint web UI.

Delete List Items in SharePoint Online using PowerShell:
Here is the script to delete list items in SharePoint online Office 365 using client side object model (CSOM) with PowerShell.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/"
$ListName="Projects"

$UserName="admin@crescent.com
$Password ="Password goes here"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
 
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Context.Credentials = $credentials
  
#Get the List
$List = $Context.web.Lists.GetByTitle($ListName)
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()) 
$Context.Load($ListItems)
$Context.ExecuteQuery()       

write-host "Total Number of List Items found:"$ListItems.Count

    if ($ListItems.Count -gt 0)
    {
        #Loop through each item and delete
        For ($i = $ListItems.Count-1; $i -ge 0; $i--)
        {
            $ListItems[$i].DeleteObject()
        } 
        $Context.ExecuteQuery()
        
        Write-Host "All List Items deleted Successfully!"
    }
 
Please note, these items are not moved to the Recycle Bin but deleted permanently! This PowerShell script could be quite helpful when dealing with deleting bulk items from a huge list.

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


How to Delete a List in SharePoint Online using CSOM-PowerShell

Requirement: Delete list in SharePoint online using PowerShell.

Important: Make sure, you have SharePoint Online client run time installed on the client machine before proceeding. Download it from here: https://www.microsoft.com/en-us/download/details.aspx?id=42038

PowerShell Script to delete a List in SharePoint Online:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
##Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/"
$ListName="Projects"

$UserName="admin@crescent.com"
$Password ="Password goes here"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
 
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Context.Credentials = $credentials
  
#Get the List
$List = $Context.web.Lists.GetByTitle($ListName)
$Context.Load($List)
$List.DeleteObject()
$Context.ExecuteQuery()
Write-Host "List deleted Successfully!"

Run it in PowerShell ISE:
delete list sharepoint online powershell


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


Wednesday, October 21, 2015

How to Change Service Accounts in SharePoint 2013 using PowerShell

Change Service Accounts in SharePoint 2013
If you have created a new managed account or want to change the mapping of managed Account with SharePoint 2013 Services, Go to:
  • Central Administration >> Security 
  • Under the General Security section, click Configure Service accounts. 
  • Pick the Appropriate Service and Service Account from the Drop downs
  • Click "OK" to Save your changes
Read more: http://www.sharepointdiary.com/2014/09/configuring-managed-accounts-in-sharepoint-2013.html

PowerShell way: How to Change Service Accounts in SharePoint 2013?
Why? because not all accounts can be changed via SharePoint Central Administration UI. Here are my scripts to change various service accounts in SharePoint using PowerShell. Please note there are Four type of Service accounts we have to take care:
  1. SharePoint Service Instances like Distribution cache, Claims to windows token service, etc
  2. SharePoint Farm Service
  3. Service Application's AppPool Account 
  4. Web Application's AppPool Account
change service account in sharepoint 2016
PowerShell script to Change Service Accounts in SharePoint (E.g. Distribution Cache Service)
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Custom Function to change Service account of given service
Function Set-ServiceIdentity($svc, $UserName)
{
    #Get the current service account
    $ProcessIdentity = $svc.Service.ProcessIdentity
    
    if ($ProcessIdentity.Username -ne $UserName) 
    {
       $ProcessIdentity.Username = $UserName
       $ProcessIdentity.Update()
       Write-Host "Service Account Set!"
    }
}

#Get the Service
$Service = Get-SPServiceInstance | Where {$_.TypeName -eq "Claims To Windows Token Service"}

#Call the function to Set "Local System" Identity to given service
Set-ServiceIdentity $Service "NT AUTHORITY\SYSTEM"
The above script changes the specified service's service account.

How to change the farm service account in SharePoint 2013:
We still rely on STSADM tool to update SharePoint 2013's Farm Account. Use this command line to update SharePoint Farm's service account credentials:
stsadm -o updatefarmcredentials -userlogin "DOMAIN\username" -password "Password here"

Change Service Application Pool's Service Account: 
To change application pool's service accounts, use this PowerShell script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Custom Function to change Service account of given service
Function Set-ServiceAppPoolIdentity($SvcAppPool, $UserName)
{
    if ($SvcAppPool.ProcessAccountName -ne $UserName) 
    {
       Set-SPServiceApplicationPool $SvcAppPool -Account $UserName
       Write-Host "Application Pool Service Account Updated!"
    }
}

#Get the Service
$SvcAppPool = Get-SPServiceApplicationPool | Where {$_.Name -eq "Service Application App Pool"}

#Call the function to Set "Local System" Identity to given service
Set-ServiceAppPoolIdentity $SvcAppPool "Crescent\SP2016Admin"

Change Web Application App Pool Accounts:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Custom Function to change Service account of Web App Pool
Function Set-WebAppPoolIdentity($WebAppPool, $UserName)
{
    if ($WebAppPool.ManagedAccount.UserName -ne $UserName) 
    {
       #Get the Managed Account
       $ManagedAccount= Get-SPManagedAccount $UserName
       #Set the Managed Account
       $WebAppPool.ManagedAccount = $ManagedAccount
       $WebAppPool.Update()
       Write-Host "Web Application App Pool Account Updated!"
    }
}

#Get Web App's App Pool
$WebAppPool = (Get-SPWebApplication "http://intranet.crescent.com").ApplicationPool

#Call the function to Set the Managed Account to Web App Pool
Set-WebAppPoolIdentity $WebAppPool "Crescent\SPAdmin"


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


How to Delete a Service Application in SharePoint 2013 using PowerShell

Requirement: Delete SharePoint 2010/2013 Service Application using PowerShell.

How to Delete a Service Application in SharePoint 2013:
  • Go to SharePoint 2013 Central Administration site 
  • Navigate to Application Management >> Manage service applications
  • In the Manage Service Applications page, Select the Service application that you want to delete.
  • click Delete button from the Ribbon.
     how to delete service application in powershell sharepoint 2013
  • You'll get a confirmation dialog, select "Delete data associated with the Service Applications" if you want to delete the service application database. leave this check box if you don't want to delete the Service application's database.
  • Click OK to delete the service application. Once deleted, you'll get the confirmation dialog.
     sharepoint 2010 delete service application powershell force
Delete a Service Application in SharePoint 2013 using PowerShell
At times you may have to use PowerShell in scenarios such as you are unable to delete a Service application as it may corrupted.To get rid of a Service Application and remove it completely using PowerShell? Well, Here are the PowerShell cmdlets to Help you!

To remove a service application from PowerShell, use Remove-SPServiceApplication cmdlet.
Syntax: 
Remove-SPServiceApplication {Service-App-ID} [-RemoveData]
E.g.
Remove-SPServiceApplication "222b3f48-746e-4cd2-a21c-018527554120" -RemoveData

Remove-SPServiceApplication needs the GUID of the target service application we want to delete, isn't it? So, How to get the Service Application ID? Here is how:

Run: Get-SPServiceApplication cmdlet, It gets you the below result with ID field:

delete service application using powershell sharepoint 2010

PowerShell Script to Delete a SharePoint 2013 Service Application:
Lets force delete a service application using its display name with PowerShell.
#Display Name 
$DisplayName="Excel Services Application"

#Get the Service Application from its Display Name
$SeviceApp = Get-SPServiceApplication -name $DisplayName

#Delete the Service Application
Remove-SPServiceApplication $SeviceApp -removedata -confirm:$false

Get Service Application from Its type name and remove:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Type Name String
$TypeName="Usage and Health Data Collection Service Application"

#Get the Service Application from its Type
$SeviceApp = Get-SPServiceApplication | Where {$_.TypeName -eq $TypeName}

#Delete the Service Application
Remove-SPServiceApplication $SeviceApp -removedata -confirm:$false 

Here is the Type Name of all service Applications:
Type
Access Services Web Service Application
Access Services 2010 Web Service Application
App Management Service Application
Application Discovery and Load Balancer Service Application
Business Data Connectivity Service Application
Excel Services Application Web Service Application
Machine Translation Service
Managed Metadata Service
PerformancePoint Service Application
PowerPoint Conversion Service Application
Search Administration Web Service Application
Search Service Application
Secure Store Service Application
Security Token Service Application
State Service
Usage and Health Data Collection Service Application
User Profile Service Application
Visio Graphics Service Application
Work Management Service Application
Word Automation Services
All above cmdlets removes service application and its proxy!

How to delete a service application proxy: 
If you want to delete the service application proxy alone, use: Remove-SPServiceApplicationProxy cmdlet:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Type Name String
$TypeName="Machine Translation Service Proxy"

#Get the Service Application Proxy from its Type
$SeviceAppProxy = Get-SPServiceApplicationProxy | Where {$_.TypeName -eq $TypeName}

#Remove the Service Application Proxy
Remove-SPServiceApplicationProxy $SeviceAppProxy -removedata -confirm:$false


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


Tuesday, October 20, 2015

Configure Variations Feature in SharePoint 2013 - Step by Step

What is Variation in SharePoint 2013?
Variations feature provides multi-lingual support for SharePoint 2013 sites. It help us to manage multilingual sites by making the same content available to specific language audiences across different sites by maintaining customizable copies of the content from the source variation in each target variation. A variation consists of a set of labels (sub-sites: Each site for one variation) that is used to create a set of sites in a site collection. For example, if you want four language variations of your site, you must create four labels, one for each language.
Important: Variations feature relies on Language packs and "SharePoint Server Publishing feature", So it works only on Publishing site template or sites with publishing feature activated!
Configure variation in SharePoint 2013:
Configuring variations in SharePoint 2013 is quite a easy task, just follow below steps:
Info: SharePoint 2013 Variation feature content synchronization is a unidirectional process! It syncs content from a source variation site to one or more target variation sites

Set variations settings:
To setup variation in SharePoint 2013, start with specifying settings for Variations.

Go to Site Settings >> Site Collection Administration >> Click on "Variations Settings "to set variations
settings. These settings are self-explanatory:
  • Create Everywhere -  Selected by default, this means any content created in source label will propagate to all target variations.  Sync will happen automatically
  • Create Selectively -  Variation should be triggered manually 
  • Recreate Deleted Target Page - Page should be re-created on a target variation site if the page was deleted 
  • Update Target Page Web Parts - Source web part changes updated to the target sites 
  • Notification - Email to label contact person
variation settings sharepoint 2013
These settings can be changed if needed, otherwise leave all settings to default and click OK.


Create variation label SharePoint 2013:
After configuring variation settings, proceed with creating variation labels. The very first variation label you are creating will be the "Source Variation" site. In our case, its English, Lets create it.
  • Language: This setting defines SharePoint User interface elements of the variation site. Choices appear on the site template language drop-down depends on the language packs installed.
  • Locale: Locale determines the language site based on your browser settings. It automatically redirects the browser from Variation home to target variation site. Locale helps in creating content in different languages. 
  • Variation Home: is the location site where sub sites for all labels will be created
  • Specify the Label Name for source variation and choose Publishing site template as "Publishing site". 
  • Click "OK" button to create source variation.
create variation labels

Now the source variation has been created. Proceed with creating target variation(s).

Create variation Target Labels:
Lets create target variation for "Arabic" site. Go to Site settings >> Click on "Variation Label" >> Click on "New Label". This time, You'll get a wizard for creating target variations.
  • On "Configure Your Target Label" page, Select the Site Template Language. This depends on language packs you deployed to the SharePoint server. E.g Install Arabic language pack if you want to configure variation for Arabic & to choose Arabic as as a site template language! Select locale for target variation, and then click on "Continue" button.
    SharePoint 2013 create variation
  • Run through the wizard to create a new target variation.  Choose Translation options.  I have  selected "Allow Human and Machine translation" and selected target language as "Arabic".
    create variation in sharepoint 2013
  • Choose the Target label behavior. I've selected the option to push content updates automatically from source label to target label
     language variation in sharepoint 2013
  • Name your Target label.
    Setup Variation Settings
  • Review and Click on Finish to complete target variation label creation.
    variation set up sharepoint 2013

Create Variations Hierarchy:
Once you are done with creating labels, each label should create a variation sub-site! Click on "Create Hierarchies" link from Variation labels page in site settings, that will invoke the timer job "Variations Create Hierarchies Job Definition". This timer job will be run based on its schedule.
sharepoint 2013 variation root

If the hierarchies created successfully, you can see it in the variation labels listing as below.
variation labels sharepoint 2013
Once variation Hierarchy is created, "Hierarchy is Created" status on Variation Label page will change to "Yes" and sites are created successfully, ready to browse!

SharePoint 2013 variation hierarchy not created?
Well, the timer job runs once per hour, and you got to wait! If you don't want to wait, just trigger "Variations Create Hierarchies Job Definition" on-demand. Here is how:
  • Navigate to SharePoint 2013 Central Administration
  • Click on: Monitoring >> Review job definitions under Timer Jobs
  • Pick your web application and click on "Variations Create Hierarchies Job Definition" timer job
  • Click on "Run Now" to run this timer job.
    variation timer jobs sharepoint 2013
If required, you can change the schedule to run shorter time period too.

SharePoint 2013 Variation Timer Jobs:
Here is the list of timer jobs involved in variations feature in SharePoint:
  1. Variations Create Hierarchies Job Definition: Creates all variation sites, lists and pages from the source variation site. It runs hourly.
  2. Variations Propagate List Items Job Definition: Creates and updates list items on target variation Default, every 15 minutes.
  3. Variations Propagate Page Job Definition: Creates and updates pages on target variation after approved. Runs every 15 minutes.
  4. Variations Propagate Sites and Lists Job Definition: Creates variation sites and lists when the "Create Everywhere" option is enabled.  Runs on every 30 minutes.
Here is the snapshot from SharePoint 2013 Central Administration Timer Job definitions page:
SharePoint 2013 Variation Timer Jobs

Variation Logs in SharePoint 2013:
During the variation process, there are several timer jobs run. All activities related to this process are logged  and collected under Variation logs to provide details in troubleshooting any variation related issue such as Hierarchy creation, Page propagation, etc. 

Variation logs are located under root site collection's settings page.
  • Site Settings >> Site Collection Administration >> Variation logs 
SharePoint 2013 variation feature logs
How to test variation feature:
Once you hit variation home, It goes to the variation site based on your browser language settings. E.g. When you hit http://portal.crescent.com, It goes to http://portal.crescent.com/english if your browser language is set to English.

How does variations feature works in SharePoint 2013?
So, How does it works? Well, When you create new pages or update existing pages on source variation site, Target variation(s) automatically updated in draft mode. They'll go live in target variations when published!

Syncing Custom list and Libraries in Variation:
By default custom lists are libraries are not synced from source to destination. It needs to be manually triggered. Here is how:
  • Go to any custom list or library in source variation site
  • Click on Variations Tab >> Click on Settings
    sharepoint 2013 create variation labels
  • Select Variation labels (sites) to sync and click "Continue". You'll get "Your new variations are on the way" message.
    configure variation sharepoint 2013
  • Once done, The particular list will be propagated on selected targets.

Technet Reference Variations overview in SharePoint Server 2013

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


Sunday, October 18, 2015

Remove User from SharePoint Group using PowerShell

Remove user from SharePoint group:
From SharePoint Web interface, if you want to remove user from SharePoint group, Login as a SharePoint Administrator, navigate to:
  • Click on Site Settings Gear icon >> Click on Site Settings
  • From the Site settings page, Click on "People and Groups" link under "Users and Permissions" group
    sharepoint powershell remove user from group
  • Select the group from the left navigation by Click on the group from which you want to remove users.
    sharepoint 2013 remove user from group programmatically
  • Select the user(s) and click on Actions Menu >> Choose "Remove users from Group"
    remove user from sharepoint group using powershell
Confirm by clicking "OK". Selected users are now removed from the SharePoint Group.

Delete user from SharePoint group using PowerShell: 
If you want to remove user from SharePoint group, this PowerShell script can help:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function RemoveUser-FromGroup($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)
     {
         #sharepoint powershell delete user from group
         $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 to remove user from SharePoint group
RemoveUser-FromGroup "http://sharepoint.crescent.com/sites/Operations" "Operations Members" "Corp\DaveP"
This removes given user from specific SharePoint group. How about removing user from All groups in the site?

Remove user from all SharePoint groups
Lets remove user from All Groups in SharePoint using PowerShell
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function RemoveUser-FromAllGroups($SiteURL, $UserAccount)
{
     #Get the Web
     $web=Get-SPWeb $SiteURL
    
     #Get the User to Remove 
     $User  = $Web.EnsureUser($UserAccount)

     #Iterate through all Groups
     foreach($Group in $Web.Groups)
     {
         $GroupUser = $Group.Users | where {$_.UserLogin -eq $User.UserLogin}
         #Check if user member of the group
         if($GroupUser -ne $null)
         {
            #remove user from sharepoint group using powershell 
            $Group.RemoveUser($User)
            Write-Host "$($User) Removed from the Group: $($Group)"
         }
     }
 }

 #Call the function to remove user from all groups in the site  
 RemoveUser-FromAllGroups "http://intranet.crescent.com" "Crescent\Salaudeen"


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


Saturday, October 17, 2015

Hide "Upload" Button of a Document Library in SharePoint 2013

Requirement: Disable upload button in SharePoint document library!

But why? Because, we wanted users to fill the form by creating new document from the New drop-down and not to upload any existing documents with Upload button. So we need to hide upload button in SharePoint 2013.

Solution: CSS! Place this CSS either in Master page or script editor/content editor of the target page.

CSS Styles to hide Upload button in SharePoint 2013:
<style type="text/css">
#Ribbon\.Documents\.New\.AddDocument-Large, #Ribbon\.Documents\.New-MediumMedium-0-1
{    
               display:none !important;
}
</style>
Hide "Open with Explorer" button in SharePoint 2013 ribbon:
You may also want to disable "Open in Explorer" as it allows multiple file upload. Use this CSS to hide "Open in Explorer" from SharePoint 2013 ribbon.
#Ribbon\.Library\.Actions-LargeMedium-1-1

Result: Upload button disabled in SharePoint 2013 document library!
sharepoint 2013 hide upload document
Disable Drag and Drop feature of SharePoint 2013:
How about disabling Drag-Drop feature? Well, use this script to disable Drag and Drop feature of SharePoint 2013 document libraries:
<script type="text/javascript">
  ExecuteOrDelayUntilScriptLoaded(function() {
   g_uploadType = DragDropMode.NOTSUPPORTED;
   SPDragDropManager.DragDropMode = DragDropMode.NOTSUPPORTED;
}, "DragDrop.js");

How to Disable Upload Button and Drag and Drop Feature in SharePoint 2016:
Edit and Add a script editor on the target list view page (AllItems.aspx), place this code in it.
<style type="text/css">
#Ribbon\.Documents\.New\.AddDocument-Large, #Ribbon\.Documents\.New-MediumMedium-0-1, #Ribbon\.Library\.Actions-LargeMedium-1-1
{    
               display:none !important;
}

/* Hide "Drag files here to upload" message in the List view */
div.ms-dragDropAttract-subtle{
 display: none 
}
/* Upload button in Doc Lib tool bar */
#QCB1_Button2
{
 display:none !important; 
} 

</style>

//Disable Drag and Drop Upload Feature
<script type="text/javascript">
  ExecuteOrDelayUntilScriptLoaded(function() {
   g_uploadType = DragDropMode.NOTSUPPORTED;
   SPDragDropManager.DragDropMode = DragDropMode.NOTSUPPORTED;
}, "DragDrop.js");



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


Wednesday, October 14, 2015

Copy Alerts from One SharePoint List or Library to Another - Using PowerShell

Requirement: Copy Alerts from one SharePoint list to another list.

Solution: Use this PowerShell script to copy alerts between SharePoint lists or libraries.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function Copy-SPAlerts($SourceWebUrl,$SourceList, $TargetWebUrl, $TargetList)
{
    #Get the source Web & List objects
    $SourceWeb = Get-SPWeb $SourceWebUrl
    $SourceList= $SourceWeb.lists.TryGetList($SourceList)   

    #Get the Target Web & List objects
    $TargetWeb = Get-SPWeb $TargetWebUrl
    $TargetList= $TargetWeb.lists.TryGetList($TargetList)   
 
    #Get All Alerts of the Source list
    $SourceAlertsColl = $SourceWeb.Alerts | Where-Object { ($_.List.Title -eq $SourceList.Title)}
    
    write-host Found $SourceAlertsColl.count alerts in the source List!

    if($SourceAlertsColl.Count -gt 0)
    {
        foreach ($SourceAlert in $SourceAlertsColl)
        {
            #Copy alerts from source to destination
            $alert = $TargetWeb.Alerts.Add()
            $alert.Title = $SourceAlert.Title
            $alert.AlertType = [Microsoft.SharePoint.SPAlertType]::List
            $alert.User = $SourceAlert.user 
            $alert.List = $TargetList
            $alert.DeliveryChannels = $SourceAlert.DeliveryChannels
            $alert.EventType =  $SourceAlert.EventType
            $alert.AlertFrequency = $SourceAlert.AlertFrequency
            $alert.Update()

            Write-Host "Copied Alert: $($SourceAlert.Title)" -foregroundcolor Green
        }
    }

}

#Variables
$SourceWebURL="http://intranet.crescent.com/PMO"
$SourceListName="Project Documents"
$TargetWebURL="http://intranet.crescent.com/sites/projects/BI/"
$TargetListName="Project Documents"

#Call the function to Copy Alerts
Copy-SPAlerts $SourceWebURL $SourceListName $TargetWebURL $TargetListName

Remember, when you copy alerts from one list to another, it triggers "New Alert Created" E-mail as:
Copy Alerts from One List to Another List in SharePoint

You can disable alerts for time being before copying: How to Disable Alerts in SharePoint List or Library

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


Friday, October 9, 2015

PowerShell Error: Add-Type: Could not load file or assembly 'file:///C:\Program Files\Common Files\Micros oft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded

Problem: 
When trying to write a client side PowerShell script for SharePoint online, got an error:

Error: Add-Type : Could not load file or assembly 'file:///C:\Program Files\Common Files\Micros
oft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll' or one of its  dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
Add-Type: Could not load file or assembly
Verified SharePoint Server 2013 Client Components SDK is already installed to use Client side assemblies. (if not,  You can download it from: http://www.microsoft.com/en-us/download/details.aspx?id=35585)

Solution:
You need to have PowerShell 3.0 to use Client side assemblies of SharePoint online. So, download and install "Windows Management Framework 3.0" at https://www.microsoft.com/en-us/download/details.aspx?id=34595

Tips: To get your currently installed PowerShell version, type: $PSVersionTable


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


Tuesday, October 6, 2015

Copy List Items Between SharePoint Lists using PowerShell

Requirement: 
One of our SharePoint list called "News" grown rapidly and wanted to archive its contents to an another list periodically.

Solution: So the task is to copy list items between SharePoint Lists. Lets achieve it using PowerShell.
Important: Both lists should have same columns! So, have the source list saved as template and create a new list from it.
PowerShell Script to copy List Items:
#Configuration variables
$WebURL = "http://intranet.crescent.com"
$SourceListName = "News"
$TargetListName= "NewsArchive"

#Get Objects
$web = Get-SPWeb $WebURL
$SourceList = $web.Lists[$SourceListName]
$TargetList = $web.Lists[$TargetListName]

#Get all source items
$SourceColumns = $sourceList.Fields
$SourceItems = $SourceList.GetItems();

#Iterate through each item and add to target list
Foreach($SourceItem in $SourceItems)
{
    $TargetItem = $TargetList.AddItem()
    Foreach($column in $SourceColumns) 
    {
        if($column.ReadOnlyField -eq $False -and $column.InternalName -ne "Attachments")
        {
             $TargetItem[$($column.InternalName)] = $sourceItem[$($column.InternalName)];
        }
    }
   $TargetItem.Update();
}

Copy Attachments:
If you want to copy attachments, insert this code in Line#26:
#Copy Attachments
Foreach($Attachment in $SourceItem.Attachments)
{
    $spFile = $SourceList.ParentWeb.GetFile($SourceItem.Attachments.UrlPrefix + $Attachment)
    $TargetItem.Attachments.Add($Attachment, $spFile.OpenBinary())
}

What if the column Names are different?
$SourceItems = $SourceList.items
foreach ($SourceItem in $SourceItems) 
{
 write-host -foregroundcolor yellow Copying Item: $SourceItem["Title"]
 $TargetItem = $TargetList.AddItem()
 $TargetItem["Title"] = $SourceItem["Title-Column"]
 $TargetItem["Another-Field"] = $SourceItem["Another-Field"]
 $TargetItem.update()
}


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


Sunday, October 4, 2015

Get All SharePoint Service Applications - IIS App Pools - Service Account Details

From the IIS console, its tedious to find the application pools of SharePoint Service Application's, isn't it?
So, lets use PowerShell to retrieve All service application's app pool and service account details.


PowerShell to get all Service Application Names, Service App Pool and Process Account details:
Get-SPServiceApplication | Select Name, @{Name="SP AppPool Name"; Expression={$_.ApplicationPool.Name}}, `
    @{Name="IIS AppPool Name"; Expression={$_.ApplicationPool.Id}}, `
     @{Name="Service Account"; Expression={$_.ApplicationPool.ProcessAccountName}}
This script gets you all service application's app pool related data:


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


How to Copy a Site collection in SharePoint

Requirement: Clone the Production SharePoint site collection to Test environment for UAT.

Solution:
While Copy-SPSite cmdlet on SharePoint 2013 or later serves the purpose, It can clone site collection only within the same web application. What if you want to copy site collection to another web application or another farm in SharePoint? Well, follow these steps to copy site collection to same/another farm.
  1. Create a new Web application
  2. Backup the live site collection
  3. Restore the backup into the target web application
Backup the Source Site Collection:
Backup-SPSite -Identity "http://portal.crescent.com" -Path "D:\backup\portal.bak" -Force -NoSiteLock -Confirm:$False 

Restore the backup into Target Site collection:
Restore-SPSite "http://testportal.crescent.com" -Path "D:\backup\portal.bak" -Force -Confirm:$False  

You can use this method to copy a site collection to another server or another server or another web application in SharePoint.
Remember to do the following:
  • Install & Deploy any Farm level feature to the newly created Web Application from Central Admin.
  • Configure Web App settings, such as: Web Application policy, Outgoing Email settings, etc.
Related post: How to Copy SharePoint 2013 Site Collection using  Copy-SPSite PowerShell cmdlet

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


Thursday, October 1, 2015

Compare SharePoint List Items using PowerShell

Requirement: We've two task lists with hundreds of rows in it. Wanted to compare these two SharePoint Lists and extract the difference from both of them.

Solution: Lets use PowerShell script to compare and extract the difference between SharePoint lists!
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Variables for Processing
$SiteURL = "http://projects.crescent.com"
$ListOneName ="Team One Tasks"
$ListTwoName ="Tasks Two Tasks"
$ColumnToCompare="Task Name"

#Get site and List objects
$Web = Get-SPWeb $SiteURL
$ListOne = $web.lists[$ListOneName]
$ListTwo = $web.lists[$ListTwoName]

#Fetch specifc Column Values from each lists to compare
$ListOneValues = @()
$ListTwoValues = @()

$ListOne.Items| foreach { $ListOneValues+= $_[$ColumnToCompare] }
$ListTwo.Items | foreach { $ListTwoValues+= $_[$ColumnToCompare] }

#Compare
Compare-Object $ListOneValues $ListTwoValues # -PassThru

Output: Here the InputObject column gives the difference.
Compare SharePoint Lists using PowerShell

The SideIndicator simply denotes where is the difference is.
  • <= - Difference is in Left side - first object we compare
  • => - Difference is in the Right side - Second object in the comparison


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


You might also like:

Related Posts Plugin for WordPress, Blogger...