About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Monday, 25 August 2014

Powershell Script - Create custom SharePoint 2013 search managed properties

The following script will create managed properties for search. The script will accept following input paramerers

1. Search Service application - Name of your search service application

Note: The script will refer .csv file which has input data. The column header format would be as follows, add your properties under this header and save file as .csv format.The file shoulb be available in the same directory.

Name;Properties;Type;Sort;Retrieve;Refine;Search;Multivalue;Query;Safe

Steps involved

1. Save following script as psCreateSearchManagedProperties.ps1


#-----------------------------------------------------------------------------
# Name:             psCreateSearchManagedProperties.ps1 
# Description:      This script will create a list of managed properties in
#                    the SharePoint 2013 Search Service Application
#                    
# Usage:            Run the script passing paramter SearchServiceApplication
# Created By:       Vamsi Mohan Mitta
# Date:             01/07/2014
#-----------------------------------------------------------------------------

Param([Parameter(Mandatory=$true)]
      [String]
      $SearchApplication
)

if ((gsnp Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null){
    asnp Microsoft.SharePoint.Powershell
}

function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

$currentPhysicalPath = Get-ScriptDirectory

$logfile=$currentPhysicalPath + "\log.log"

Start-Transcript $logfile

$objShell = New-Object -Com Shell.Application
$folder = $objShell.BrowseForFolder(0,"Please select the folder containing your CSV file:",0)
$pathfld = $folder.Self.Path
$fullpath = Join-Path $pathfld "managed-properties.csv"

$ssa = Get-SPEnterpriseSearchServiceApplication $SearchApplication

Import-Csv -Delimiter ";" -Path $fullpath | % {

    switch ($_.Type){
        "text" {$type = 1}
        "integer" {$type = 2}
        "decimal" {$type = 3}
        "DateTime" {$type = 4}
        "YesNo" {$type = 5}
        "Binary" {$type = 6}
        "Double" {$type = 7}
        default {$type = 1}
    }
   
    if ((Get-SPEnterpriseSearchMetadataManagedProperty $_.Name -SearchApplication $ssa -ea SilentlyContinue) -eq $null){
        try {
            New-SPEnterpriseSearchMetadataManagedProperty -Name $_.Name -SearchApplication $ssa -Type $type -Retrievable:([bool]::Parse($_.Retrieve)) -Queryable:([bool]::Parse($_.Query)) -SafeForAnonymous:([bool]::Parse($_.Safe)) -EA Stop
       
            $mp = Get-SPEnterpriseSearchMetadataManagedProperty $_.Name -SearchApplication $ssa
            $mp.Searchable = [bool]::Parse($_.Search)
            $mp.Refinable = [bool]::Parse($_.Refine)
            $mp.Sortable = [bool]::Parse($_.Sort)
            $mp.HasMultipleValues = [bool]::Parse($_.Multivalue)
            $mp.Update()

            $cps = ($_.Properties).split(",")

            Write-Host "Managed property $($_.Name) successfully created." -ForegroundColor Green

            foreach ($cpname in $cps){
                try {
                    $cp = Get-SPEnterpriseSearchMetadataCrawledProperty $cpname -SearchApplication $ssa -EA Stop

                    try {
                        New-SPEnterpriseSearchMetadataMapping -SearchApplication $ssa -ManagedProperty $mp -CrawledProperty $cp

                        Write-Host "Mapping between Managed property $($_.Name) and crawled property $($cp.Name) completed successfully." -ForegroundColor Green
                    } catch {
                        Write-Host "Unable to map managed property $($_.Name) and crawled property $($cp.Name). $($error[0].Exception.Message)." -ForegroundColor Magenta
                    }
                } catch {
                    Write-Host "Crawled property $($cp.Name) not found. $($error[0].Exception.Message)." -ForegroundColor Magenta
                }
            }
        } catch {
            Write-Host "Unable to create managed property $($_.Name). $($error[0].Exception.Message)." -ForegroundColor Magenta
        }
    } else {
        Write-Host "Managed property $($_.Name) already exists." -ForegroundColor DarkYellow
    }
}

Stop-Transcript
Echo Finish


Step2: Create batch file to run the script. Save file in .bat format.

cd /d %~dp0
powershell -file ./psCreateSearchManagedProperties.ps1 -SearchApplication "Search"
pause

Happy powershell coding... please feel free to comment...

Powershell Script - Import BCS model along with permissions in SharePoint 2013

The following script will import BCS entity to SharePoint environment. The script need following as input parameters

1. Site Url
2.Admin user account
3.All users group (NT AUTHORITY\authenticated users)
4.Catalog Name (The BCS entity name which you are going to create/update)

Steps involved


Note: Make sure that, your .bdcm file should be in the current directory (where you are running your script)

1. Save following script as psDeployBCSModel.ps1

Param(           
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]           
[string]$SiteUrl,           
[Parameter(Mandatory=$true)]           
[string]$AdminUser,           
[Parameter(Mandatory=$true)]           
[string]$AllUsers,
[Parameter(Mandatory=$true)]           
[string]$CatalogName        
)

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell";
}
    
function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

function SetBcsProfileHostUrl($bdc, $siteUrl)
{
    #$catalog = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType "Catalog" -ServiceContext $siteUrl
    $property = $bdc.Properties | Where { $_.Name -eq "Profile_HostURL" }
    if ($property) {
        $bdc.Properties.Remove("Profile_HostURL")
    }
    $bdc.Properties.Add("Profile_HostURL", $siteUrl)
    write-host write-host “Successfully added BCS profile page to the model-” -ForegroundColor Green
}

#Get Current Physical Path
$currentPhysicalPath = Get-ScriptDirectory
$logfile=$currentPhysicalPath + "\log.log"
Start-Transcript $logfile

try
{
$bdc = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType Catalog -ServiceContext $SiteUrl
#$pathtobdcmfiles = Get-Location
$importFiles = Get-Childitem -path $currentPhysicalPath | Where {$_.extension -eq ".bdcm" -and $_.basename -ne "catalog"}

#$ecConvCatalog = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType "Catalog" -Name $CatalogName -ServiceContext $SiteUrl

#if($ecConvCatalog)
#{

#Remove-SPBusinessDataCatalogMetadataObject –Identity $ecConvCatalog
#write-host write-host “Successfully removed existing BCS model-” -ForegroundColor Green
#}

foreach ($file in $importFiles) {
     if($file -ne $null)
     {

         Import-SPBusinessDataCatalogModel -Path $file.FullName -Identity $bdc -force -ModelsIncluded -PropertiesIncluded -PermissionsIncluded -Verbose
         write-host write-host “Successfully imported BCS model-” $file.Name -ForegroundColor Green
    
         $claimAdmin = New-SPClaimsPrincipal -Identity $AdminUser -IdentityType WindowsSamAccountName
         $claimUsers = New-SPClaimsPrincipal -Identity $AllUsers -IdentityType WindowsSamAccountName

         $claimAdmin = New-SPClaimsPrincipal -Identity $AdminUser -IdentityType WindowsSamAccountName
         $claimUsers = New-SPClaimsPrincipal -Identity $AllUsers -IdentityType WindowsSamAccountName

         Grant-SPBusinessDataCatalogMetadataObject -Identity $bdc -Principal $claimAdmin -Right "Execute,SetPermissions,Edit,SelectableInClients"
         Grant-SPBusinessDataCatalogMetadataObject -Identity $bdc -Principal $claimUsers -Right "Execute"
         write-host write-host “Successfully granted access rights to BCS model-” $file.Name -ForegroundColor Green

         Copy-SPBusinessDataCatalogAclToChildren -MetadataObject $bdc
         write-host write-host “Successfully deployed BCS entity-” $file.Name -ForegroundColor Green
    }
}# end of for
   
SetBcsProfileHostUrl -bdc $bdc -siteUrl $SiteUrl
}
catch
{
    $Host.UI.RawUI.WindowTitle = " -- Error --"
    Write-Host -ForegroundColor Red $_.ToString()
    Write-Host -ForegroundColor Red $_.Exception.ToString()
}

Stop-Transcript


Step2: Create batch file to run the script. Save file in .bat format.

/cd /d %~dp0
powershell -file ./psDeployBCSModel.ps1 -SiteUrl "https://devpub.ec.com" -AdminUser "EC\SPBCS" -AllUsers "NT AUTHORITY\authenticated users" -CatalogName "ECConversation"
pause


Happy powershell coding... please feel free to comment...