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()