Wednesday 20 August 2014

Add users to SharePoint group using PowerShell to csv file

Below is the PowerShell code for adding user in SharePoint Group.

- Need to change some configure details in script.
- Need to chagne in CSV file like GroupName and UserID 

 
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue #Load Module
#Setvariable
#set the web application name
$varWebUrl="http://server-name/site/test/"
#set the CSV location, CSV format is [columnName(GroupName), columnName(UserID).
$varCSVLocation="C:\UserToUploadSharePointGroup\UserToUpload.csv"
#set the Log file location, where user details are save if not abel to add
$varLogFile="C:\UserToUploadSharePointGroup\UserNotAddedList.txt"
#------------------------------------------------------
$web = Get-SPWeb $varWebUrl
$count=1
$Time=Get-Date
Write-Host Start Time:$Time -ForegroundColor Yellow `n
# Import the .csv file, and specify manually the headers, without column name in the file
IMPORT-CSV $varCSVLocation |
  ForEach-Object {
    $group=$_.GroupName
    $user=$_.UserID
    $groupName = $web.SiteGroups[$group]
    Try
    {
        $user = $web.Site.RootWeb.EnsureUser($user)
        $groupName.AddUser($user)
        Write-Host -ForegroundColor green  ID:$count `t $user `t Users Added Successfully. 
    }
    Catch [system.exception]
    {
        Write-Host -ForegroundColor Red ID:$count `t $user `t Users is not added.
        $output= "ID:$count" +"  User: " +$user
        $output | Out-file $varLogFile -Append
    }
    $count=$count+1
  }
 $Web.Dispose()
 $EndTime = Get-Date
 Write-Host `n End Time:$EndTime -ForegroundColor Yellow
 

Thursday 7 August 2014

Content type subscriber timer job recreate in sharePoint 2013 for Web Application level

Issue/Problem: - Due to some unknown issue we are not able to find out the OOB publishing content job for a particular web application. We are performing many option to recreate the job but not able to recreate the Out of box "Content Type Subscriber" timer job in web application level.

Resolve: - Run the PowerShell script for Disable and Enable the “Content Type Subscriber” job. Feature is activated when the web app is created. However, something is causing the timer job to not get created. You can run these two PowerShell commands to re-create the timer job. Change the URL to yours

Below is the following script:-

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue #Load Module
# Disables the feature because it's still running in the background when the web app was created.
Disable-SPFeature -Identity ContentTypeSyndication -Url http://webappurl.contoso.com -Confirm:$false

# Enables the feature which will show up on the Timer Job Definitions
Enable-SPFeature -Identity ContentTypeSyndication -Url http://webappurl.contoso.com

Tuesday 29 July 2014

SharePoint Farm BackUp


Config DB backup can be accomplish by two ways through PS as below:

 - Full Config Back up of DB:
    Backup-SPConfigurationDatabase -Directory -DatabaseServer  -DatabaseName -Verbose
 - Configuration details alone
    Backup-SPFarm -Directory \\file_server\share\Backup -BackupMethod full -ConfigurationOnly

Full Farm Backup


    Backup-SPFarm – Directory “\\server_name\Full_Farm_Backup” –backupmethod Full

Wednesday 16 July 2014

How to take screenshot using VBScript

Dim dt
dt=now
set WshShell = CreateObject("WScript.Shell")
WshShell.Run "taskmgr.exe"
WScript.Sleep 2000
WshShell.SendKeys "% x"
Set oWordBasic = CreateObject("Word.Basic")
oWordBasic.SendKeys "{prtsc}"
oWordBasic.AppClose "Microsoft Word"
WScript.Sleep 2000
WshShell.SendKeys "% n"
WshShell.Run("C:\\ScreenShots\\ScreenShots.docx")
WScript.Sleep 1000
WshShell.SendKeys "% x"
WScript.Sleep 1000
WshShell.SendKeys dt
WshShell.SendKeys "^v"
WScript.Sleep 500
WshShell.SendKeys "^s"
WScript.Sleep 500
WshShell.SendKeys "{ENTER}"
WScript.Sleep 5000
WshShell.Run "taskkill /im winword.exe", , True
WScript.Sleep 500
WshShell.SendKeys "{ENTER}"
Set WshShell=Nothing
WScript.Quit

Monday 14 July 2014

Set Index column in list in SharePoint 2013 using PowerShell


Following is the code
********************************************************
Start-SPAssignment
$subsite = Get-SPWeb http://perimeter.portal.qc.atc.local/apps/mngr

Function removeIndex ()
{
Param ($list,$InternalFldName)

    try
        {
        Write-Output "The searching  field $InternalFldName";

        $fldToIndex =$list.Fields.GetFieldByInternalName($InternalFldName);                                                

        Write-Output "The field $fldToIndex has been found";

            try
            {
               $index= $list.FieldIndexes.Item($fldToIndex.Id)
               $fldToIndex.Indexed = $true;  
               $list.FieldIndexes.Delete($fldToIndex.Id);
               Write-Output ("The indexed {0} has been removed" -f $fldToIndex.Title) ;
             
            }
            catch
            {
               Write-Output "The field $fldToIndex is already non-indexed"
            }

        }
    catch
        {
         $error[0]
        }

}


Function AddIndex ()
{
Param ($list,$InternalFldName)

    try
        {
        Write-Output "The searching  field $InternalFldName";

        $fldToIndex =$list.Fields.GetFieldByInternalName($InternalFldName);                                                

        Write-Output "The field $fldToIndex has been found";

            try
            {
               $index= $list.FieldIndexes.Item($fldToIndex.Id)
               Write-Output "The field $fldToIndex is already indexed"
            }
            catch
            {
                $fldToIndex.Indexed = $true;  
                $list.FieldIndexes.Add($fldToIndex);
                Write-Output ("The field {0} has been indexed" -f  $fldToIndex.Title);
            }

        }
    catch
        {
         $error[0]
        }

}

$listsToIndex = @{
"apps/mngr/lists/IMDocument"="Mngr_Id";
}

foreach ($lstToIndex in $listsToIndex.GetEnumerator())
{

Write-Output ( "Index  {0} for list {1} ..." -f $lstToIndex.Value,  $lstToIndex.Key );


$lst = $subsite.GetList($lstToIndex.Key)
$InternalFldName=$lstToIndex.Value

if (($lst -ne $null) -and ($InternalFldName -ne $null))
{
    #removeIndex  $lst $InternalFldName
    addIndex $lst $InternalFldName
    write-Output "~~~~~~~~~~~~~~~~~~~~"
 }
else
{
    Write-Output "The predefined list has error for $lst"
}

}

Monday 7 April 2014

Result Source redirection in Search Result page in SharePoint 2013

 <script type="text/javascript">
 if(window.location.hash!='#'){
     window.onload = function() {
            if(!window.location.hash) {
            window.location = window.location + '#';
     window.location.reload();
               }
             }
        }
        var browserlanguageCode = window.navigator.userLanguage || window.navigator.language;
        var setlanguageCode = "";
        var codeChinese = new Array('zh-tw', 'zh-cn', 'zh-hk', 'zh-sg');
        var codeSpanish = new Array('es-mx','es-gt','es-cr','es-pa','es-do','es-ve','es-co','es-pe','es-ar','es-ec','es-cl','es-uy','es-py','es-bo','es-sv','es-hn','es-ni','es-pr');

        for (i = 0; i <= codeChinese.length; i++) {
            if (codeChinese[i] == browserlanguageCode){
                setlanguageCode = "Chinese";
  }
        }
        for (i = 0; i <= codeSpanish.length; i++) {
            if (codeSpanish[i] == browserlanguageCode){
                setlanguageCode = "Spanish";
  }
        }
       if (typeof Srch.U.fillKeywordQuery != 'undefined') {
            var originalFillKeywordQuery = Srch.U.fillKeywordQuery;
            Srch.U.fillKeywordQuery = function (query, dp) {
               
  if (setlanguageCode == "Spanish") {
                    //Search Result source for Spanish
                    dp.set_sourceID('d8fbaafc-b47c-4436-8b21-0ceac0adb8ae');
                } else if (setlanguageCode == "Chinese") {
                    //Search Result source for Chinese
      dp.set_sourceID('d7193f50-e891-5dbf-9eee-2fd82d41b17e');
                } else {
             dp.set_sourceID('d7193f50-0201-4dbf-9eee-2fd82d41b17e');
                }
                originalFillKeywordQuery(query, dp);
            };
        }
 </script>

Saturday 5 April 2014

Add Terms in Term Set in Sharepoint 2013 Managed Metadata Service Application using Powershell

Below code for add terms in term set in SharePoint 2013 using Power Shell Script.


function ImportTermSet([Microsoft.SharePoint.Taxonomy.TermStore]$store, [string]$groupName, [PSCustomObject]$termSet) {  
  function ImportTerm([Microsoft.SharePoint.Taxonomy.Group]$group, 
                      [Microsoft.SharePoint.Taxonomy.TermSet]$set, 
                      [Microsoft.SharePoint.Taxonomy.Term]$parent, 
                      [string[]]$path) {        
    if ($path.Length -eq 0) {
      return
    } elseif ($group -eq $null) {
      $group = $store.Groups | where { $_.Name -eq $path[0] }
      if ($group -eq $null) {
        $group = $store.CreateGroup($path[0])
      }
    } elseif ($set -eq $null) {
      $set = $group.TermSets | where { $_.Name -eq $path[0] }
      if ($set -eq $null) {
 Write-Host “Create $path[0]“
        $set = $group.CreateTermSet($path[0])
Write-Host “Created $path[0]“ 
      }
    } else {
      $node = if ($parent -eq $null) { $set } else { $parent }
      $parent = $node.Terms | where { $_.Name -eq $path[0] }       
      if ($parent -eq $null) {
        $parent = $node.CreateTerm($path[0], 1033)
      } 
    }
    
    ImportTerm $group $set $parent $path[1..($path.Length)]                                     
  }
  
  $termSetName = $termSet[0].”Term Set Name”    
  $termSet | where { $_.”Level 1 Term” -ne “” } | foreach {
    $path = @($groupName, $termSetName) + @(for ($i = 1; $i -le 7; $i++) { 
      $term = $_.”Level $i Term”
        if ($term -eq “”) {
          break
        } else {
          $term
        }
      }
    )
        
    ImportTerm -path $path
  }
}

$url = “http://vlad.test.loc”

$session = Get-SPTaxonomySession -Site $url
$store = $session.TermStores["Test - Managed Metadata Service Application"] 
$folder= Get-ChildItem -Path C:\Termset\ -Recurse -Include *.csv
$folder | ForEach-Object {
$FileName ="C:\Termset\"+$_.Name
$termSet = Import-Csv $FileName
ImportTermSet $store "Test Term Sets" $termSet
}
$store.CommitAll() 



Thursday 20 February 2014

Custom and OOB Web Part details in one or more site collection in SharePoint

Create one CSV file with site collection url detials in "SiteCollectionName" columns.

Below is the power shell script to fetch the web part detials in Power Shell Grid View


if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
function enumerateWebParts($Url) {
    $site = new-object Microsoft.SharePoint.SPSite $Url   
                foreach($web in $site.AllWebs)
                {
        if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web))
                                {
            $pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
            $pages = $pWeb.PagesList
            foreach ($item in $pages.Items)
                                                {
                $fileUrl = $webUrl +"/" + $item.File.Url
                $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);
                $wps = $manager.webparts
                $wps | select-object @{Expression={$pWeb.Url};Label="Web URL"},@{Expression={$fileUrl};Label="Page URL"}, DisplayTitle, IsVisible, @{Expression={$_.GetType().ToString()};Label="Type"}
            }
        }
        else {
            $pages = $null
            $pages = $web.Lists["Site Pages"]           
                                                if ($pages)
                                                {               
                                                foreach ($item in $pages.Items)
                                                {
                    $fileUrl = $webUrl +"/" + $item.File.Url
                    $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);
                    $wps = $manager.webparts
                    $wps | select-object @{Expression={$pWeb.Url};Label="Web URL"},@{Expression={$fileUrl};Label="Page URL"}, DisplayTitle, IsVisible, @{Expression={$_.GetType().ToString()};Label="Type"}
                }
            }
            else {
            }
        }        Write-Host"… completed processing" $web
    }
}

#Get the CSV file and connect to the SharePoint list
$vessellist = import-csv -Path "C:\SiteCollectionName.csv"
$itemCount = $vessellist.Count;
$currentItem = 1;
foreach($item in $vessellist)
{
    #Update the progress information
    Write-Progress -Id 1 -ParentId 0 -Activity "Listing Data In CSV File" -PercentComplete (($currentItem/$itemCount)*100) -Status "Item $currentItem or $itemCount";
    $currentItem++;
    #Write the rows VESSEL_NAME column to the console
                $row += enumerateWebParts($item.SiteCollectionName)
}
$row | Out-GridView

Saturday 15 February 2014

Applying/Change the CustomMasterUrl and MasterUrl in master page setting in SharePoint using PowerShell

Provide the URL in $webAppUrl and Below is the code details:-

param($webAppUrl)
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint.Administration")
 
$site=New-Object Microsoft.SharePoint.SPSite($webAppUrl)
$web = $site.openweb();
$web.AllowUnsafeUpdates=$true;
$MasterPageURL="/_catalogs/masterpage/XYZ_publishing.master"
$web.CustomMasterUrl=$MasterPageURL
$web.MasterUrl=$MasterPageURL
$web.Update()
$web.AllowUnsafeUpdates=$false;
$outputText = "XYZ publishing master page is applying in "+ $web.Name +" site."
write-output $outputText
                                
$web.Dispose()
$site.Dispose()

Friday 14 February 2014

Upload Master Page in SharePoint Site using PowerShell

At first you create one folder like “Master Page Unload File” under the folder creates one more folder like “Doc” with two other files UploadMasterPages.bat and UploadMasterPages.ps1.
Master Page Unload File.
-  Doc
                - MasterPage.aspx (Store your master page under Doc folder)
-  UploadMasterPages.bat
-  UploadMasterPages.ps1

Please see the below code part:-   For UploadMasterPages.ps1


param($webAppUrl)
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Sharepoint.Administration")
 
$checkInComment="Check In"
$publishComment="published"
$approveComment="Approved"
$logfile = "UploadMasterPage_$(get-date -f yyyyMMdd_hhmmss).log"
$spsite = new-object Microsoft.Sharepoint.SPSite($webAppUrl);
$web = $spsite.RootWeb;
 
    $masterPageList = ($web).GetFolder("Master Page Gallery")
    # Get file system path
$filesfolde = Split-Path $script:MyInvocation.MyCommand.Path
 
$masterPageLocalDir = $filesfolde + "\Doc"
    #For upload all files in document library from file system
     
foreach ($file in Get-ChildItem $masterPageLocalDir)
      {
      $web.AllowUnsafeUpdates=$true;
     
try
{
      if ([Microsoft.SharePoint.Publishing.PublishingSite]::IsPublishingSite($spsite))
      {
     
      $stream = [IO.File]::OpenRead($file.fullname)
          $destUrl = $web.Url + "/_catalogs/masterpage/" + $file.Name;
            $masterPageFile=$web.GetFile($destUrl)
      write-host($masterPageFile)
      write-host($destUrl)
      write-host($stream)
           if($masterPageFile.CheckOutStatus -ne "None")
            {
                       
                        $web.AllowUnsafeUpdates  = $true;
                        $masterPageList.files.Add($destUrl,$stream,$true)
                       
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);                              
                        $masterPageFile.Publish($publishComment);                       
                        $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name+ " Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
            }
          else
            {
                        $masterPageFile.CheckOut();
                        try{
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        }
                        catch
                        {
                        write-Output $_
                        }
                        $stream.close()                                       
                         $masterPageFile.CheckIn($checkInComment);                                     
                         $masterPageFile.Publish($publishComment);                                     
                         $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name +  " Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
            }
      }
     
      else
      {
     
            $stream = [IO.File]::OpenRead($file.fullname)
            $destUrl = $web.Url + "/_catalogs/masterpage/" +$file.Name
            $masterPageFile=$web.GetFile($destUrl)
             if($masterPageFile.CheckOutStatus -ne "None")
              {
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);                              
                        $masterPageFile.Publish($publishComment);                       
                        $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name +  "Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
               }
             else
               {
                        $masterPageFile.CheckOut();
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                       
                         $masterPageFile.CheckIn($checkInComment);                                     
                         $masterPageFile.Publish($publishComment);                                     
                         $masterPageFile.Approve($approveComment);
                        $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name+ "Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
              }
      }
     
     
}
catch
{
try
         {
     
           
            $stream = [IO.File]::OpenRead($file.fullname)
            $destUrl = $web.Url + "/_catalogs/masterpage/" + $file.Name;
            $masterPageFile=$web.GetFile($destUrl)
             if($masterPageFile.CheckOutStatus -ne "None")
               {
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);
                       $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name+ " Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
               }
              else
                {
 
                        $masterPageFile.CheckOut();
                        $masterPageList.Files.Add($destUrl,$stream,$true)
                        $stream.close()                                
                        $masterPageFile.CheckIn($checkInComment);
                       $masterPageFile.Update();        
                         $web.Update();
                          $web.AllowUnsafeUpdates  = $false;
                          $outputText = $file.Name +" Master Page uploaded on $web site"
                                write-output $outputText
                                write-output $outputText |  out-File $logfile -Append
               }
         }
      catch
         {
            write-Output $_ | out-File $logfile -Append
         } 
}
}
$web.dispose();
$spsite.dispose();

----------------------------------------------------------------------------------------------------
 Please see the below code part:-   For UploadMasterPages.bat

cls
 set startDate=%date%
set startTime=%time%
 set sdy=%startDate:~10%
set /a sdm=1%startDate:~4,2% - 100
set /a sdd=1%startDate:~7,2% - 100
set /a sth=%startTime:~0,2%
set /a stm=1%startTime:~3,2% - 100
set /a sts=1%startTime:~6,2% - 100
set timestamp=%sdm%-%sdd%-%sdy%-%sth%-%stm%-%sts%
 time /t
 powershell.exe Set-ExecutionPolicy RemoteSigned
powershell.exe -noexit .\UploadMasterPages.ps1 "http://server-name.com/site/"
 time /t