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 user profile properties in SharePoint 2013

The powershell script will create custom user profile properties by reading data from xml configuration file. The script accepts following input parameters

1. SiteUrl - Site colletion url
2. ManagedMetaDataServiceName - MMS service app name

Points to be noted

1. The MMS service is required, as one of the custom property gets data from predefined term set.
2. We need xml file which has required configuration.

Steps involved

1. Save following as xml file format, you can add as many as configurations you want and save as costumUserProfileProperties.xml and should be in the root directory of the script where you are running...

<?xml version="1.0" encoding="utf-8" ?>
<UserProfileProperties>
 
<Property Name="SkillSets" DisplayName="SkillSets" Type="string (Multi Value)"  IsTaxonomic="True" TermSet="Skills" Length="500" Privacy="Public" PrivacyPolicy="mandatory" IsVisibleOnEditor="$true"
IsVisibleOnViewer="$true"  IsUserEditable ="$true"></Property>

<Property Name="Interests" DisplayName="Interests" Type="string (Multi Value)"  IsTaxonomic="True" TermSet="Skills" Length="500" Privacy="Public" PrivacyPolicy="mandatory" IsVisibleOnEditor="$true"
IsVisibleOnViewer="$true"  IsUserEditable ="$true"></Property>

</UserProfileProperties>

   

2. Save following script as psCreateCustomUserProfileProperty.ps1
#-----------------------------------------------------------------------------
# Name:             psCreateCustomUserProfileProperty.ps1 
# Description:      This script will create termset names as 'Skills'
#                    and creates following user profile properties
#                   'Skills' & 'Interests'
#                    
# Usage:            Run the script by passing the paramter $SiteUrl,
#                   ManagedMetaDataServiceName
# Created By:       Vamsi Mohan Mitta
# Date:             01/07/2014
#-----------------------------------------------------------------------------

Param([Parameter(Mandatory=$true)]
      [String]
      $SiteUrl,
      [Parameter(Mandatory=$true)]
      [String]
      $ManagedMetaDataServiceName     
)

if ((gsnp Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null){
    asnp Microsoft.SharePoint.Powershell
}
#Do not modify anything in the script from here onwards
function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

#Get Current Physical Path
$currentPhysicalPath = Get-ScriptDirectory

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

Start-Transcript $logfile

#Connect to the Metadata Service
$taxSite = get-SPSite $SiteUrl    # Central Admin URL  
$taxonomySession = Get-SPTaxonomySession -site $taxSite
$termStore = $taxonomySession.TermStores[$ManagedMetaDataServiceName]    # Meata data service name
write-host “Connection made with term store -” $termStore.Name -ForegroundColor Green

$termGroupName = "ECTermGroup"
#Create a group
      if ($termStore.Groups[$termGroupName] -eq $null)
      {
        $termGroup = $termStore.CreateGroup($termGroupName)
        $termStore.CommitAll()
        write-host “Successfully created term group -” $termGroupName -ForegroundColor Green
      }
      else
      { write-host “Term Group already -” $termGroupName " exists" -ForegroundColor Blue }

#Connect to existing term group
$termGroup = $termstore.groups[$termGroupName];

#TERM SETS
#Create a term set

    if($termGroup.TermSets["Skills"] -eq $null)
    {
    $createTermSet = $termGroup.CreateTermSet("Skills")
    $termStore.CommitAll()
    write-host “Successfully created term set” -ForegroundColor Green
    }
    else
      { write-host “Term Set already exists" -ForegroundColor Blue }


#Connect to existing term set
$termset = $termGroup.Termsets["Skills"]

$term = $termSet.CreateTerm("Sea wall",1033)
$term.SetDescription(“Sea wall”, 1033)
$term.CreateLabel("Seawall”, 1033, $false)

$term = $termSet.CreateTerm("Tunnels and bridges",1033)
$term.SetDescription(“Tunnels and bridges”, 1033)
$term.CreateLabel("Tunnelsandbridges”, 1033, $false)


$term = $termSet.CreateTerm("Water pipelines",1033)
$term.SetDescription(“Water pipelines”, 1033)
$term.CreateLabel("Waterpipelines”, 1033, $false)

$term = $termSet.CreateTerm("Desalination plants- Land reclamation",1033)
$term.SetDescription(“Desalination plants- Land reclamation”, 1033)
$term.CreateLabel("Desalinationplants”, 1033, $false)

$TermSet.IsOpenForTermCreation = $true;

# Contribute permission on term group
$user = "c:0(.s|true"
$termGroup.AddContributor($user)


$termStore.CommitAll()

#----------------This service application is the default storage location for column specific term sets---------------------------------------------------------------


# This service application is the default storage location for column specific term sets.  on proxy peroperty select this
# Get Metadata service application proxy
$metadataserviceapplicationname = $ManagedMetaDataServiceName
Set-SPMetadataServiceApplicationProxy -Identity $metadataserviceapplicationname -DefaultSiteCollectionTaxonomy:$true

#$metadataserviceapplicationproxy = get-spmetadataserviceapplicationproxy $metadataserviceapplicationname
#$metadataserviceapplicationproxy.Properties["IsDefaultSiteCollectionTaxonomy"] = $true

# Create a custom property with above term set as input.

#----------------Get the xml file---------------------------------------------------------------

 #[xml]$xmlData=Get-Content $xmlFilePath

 $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
 $filenamne = $scriptPath + '\' + "costumUserProfileProperties.xml"
 [xml]$xmlData=Get-Content $filenamne

#----------------Create new custom User Profile properties---------------------------------------------
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorVariable err -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")

function CreateUserProfileProperties($SiteUrl,$ManagedMetaDataServiceName)
{    
     
#Connect to the Metadata Service
$taxSite = get-SPSite $SiteUrl  
$taxonomySession = Get-SPTaxonomySession -site $taxSite
$termStore = $taxonomySession.TermStores[$ManagedMetaDataServiceName]

#Connect to existing term group
$termGroup = $termstore.groups["ECTermGroup"];
$termSetSkill = $termGroup.TermSets["Skills"]


      #$site = Get-SPSite $xmlData.UserProfileProperties.SiteURL
      $site = Get-SPSite $SiteUrl
      $context = Get-SPServiceContext($site)
      $upcm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($context);     
      $ppm = $upcm.ProfilePropertyManager
      $cpm = $ppm.GetCoreProperties()
      $ptpm = $ppm.GetProfileTypeProperties([Microsoft.Office.Server.UserProfiles.ProfileType]::User)
      $psm = [Microsoft.Office.Server.UserProfiles.ProfileSubTypeManager]::Get($context)
      $ps = $psm.GetProfileSubtype([Microsoft.Office.Server.UserProfiles.ProfileSubtypeManager]::GetDefaultProfileName([Microsoft.Office.Server.UserProfiles.ProfileType]::User))
      $pspm = $ps.Properties
      $xmlData.UserProfileProperties.Property | ForEach-Object{
            $property = $pspm.GetPropertyByName($_.Name)         
            if($property -eq $null)
            {
                $Privacy=$_.Privacy
                $PrivacyPolicy=$_.PrivacyPolicy
                $coreProp = $cpm.Create($false)
                $coreProp.Name = $_.Name
                $coreProp.DisplayName = $_.DisplayName
                $coreProp.Type = $_.Type
                $coreProp.Length = $_.Length
                 #$coreProp.IsTaxonomic=[Microsoft.SharePoint.Taxonomy.TermSet]$_.IsTaxonomic

                 $coreProp.TermSet=$termSetSkill

                $cpm.Add($coreProp)
                $profileTypeProp = $ptpm.Create($coreProp);
                $profileTypeProp.IsVisibleOnEditor = $true;
                $profileTypeProp.IsVisibleOnViewer = $true;

                $ptpm.Add($profileTypeProp)

                $profileSubTypeProp = $pspm.Create($profileTypeProp);
                $profileSubTypeProp.DefaultPrivacy = [Microsoft.Office.Server.UserProfiles.Privacy]::$Privacy
                $profileSubTypeProp.PrivacyPolicy = [Microsoft.Office.Server.UserProfiles.PrivacyPolicy]::$PrivacyPolicy
                $profileSubTypeProp.IsUserEditable = $true;  
                $profileSubTypeProp.AllowPolicyOverride        
               
                $pspm.Add($profileSubTypeProp)
                  write-host -f yellow $_.Name property is created successfully                
            }
            else
            {
               write-host -f yellow $_.Name property already exists
            }
      }
}
#----------------Calling the function--------------------------------------------- 
 CreateUserProfileProperties -SiteUrl $SiteUrl -ManagedMetaDataServiceName $ManagedMetaDataServiceName

 Stop-Transcript
 Echo Finish


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

cd /d %~dp0
powershell -file  ./psCreateCustomUserProfileProperty.ps1 -SiteUrl "xxxxx" -ManagedMetaDataServiceName "MMS_Proxy"
pause

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

Powershell Script - Modify Sharepoint web.config file entries

The following script will add/update SharePoint web.config file entries. The script accepts following input parameters. 

1. WebAppUrl - SharePoint web application url
2.WebConfigPath - Path for the SharePoint web application virtual directory

 Points to be noted
1. The following script backup existing web.config and add entries under configuration/appSettings & configuration/connectionStrings
 2. Provide input data in the form of .csv file with the separator as "$" with following header
 Configuration$Key$Value    
 Configuration is nothing but - the node where you want to add entries
3. The csv file should be in the same directory


Steps involved

1. Save following script as psUpdateSPWebApp.config.ps1


Param([Parameter(Mandatory=$true)]
      [String]
      $WebAppUrl,
      [Parameter(Mandatory=$true)]
      [String]
      $WebConfigPath
)

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

$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 "xxxxx.csv"

# Show Farm BuildVersion to ensure the SharePoint .net library is loaded
$localFarm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$localFarm.BuildVersion

# store some settings and objects in variables
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppUrl)
$farmServices = @($webapp.Farm.Services | where-object { $_.TypeName -eq "Microsoft SharePoint Foundation Web Application" } )[0]


$currentDate = Get-Date -format MM-dd-yyyy-hh_mm_s # month-day-year - hours_mins_seconds
$backup = $WebConfigPath + "_$currentDate" + ".bak"

# Get the content of the config file and cast it to XML and save a backup copy labeled .bak followed by the date
$xml = [xml](get-content $WebConfigPath)
#save a backup copy
$xml.Save($backup)

$connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")

        if ($connectionStringsNode -eq $null)
        {        
        Write-Host "connectionStrings node does not exist. Adding the node..." -ForegroundColor Cyan           
        # Node does not exist. So create it        
        $root = $xml.get_DocumentElement()                 
        $connectionStringsNode = $xml.CreateNode('element',"connectionStrings","")
        $configurationNode = $xml.configuration.AppendChild($connectionStringsNode)
        $connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created connectionStrings node" -ForegroundColor Green           
        }

$appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")

        if ($appSettingsNode -eq $null)
        {        
        Write-Host "appSettings node does not exist. Adding the node..." -ForegroundColor Cyan           
        # Node does not exist. So create it        
        $root = $xml.get_DocumentElement()                 
        $appSettingsNode = $xml.CreateNode('element',"appSettings","")
        $configurationNode1 = $xml.configuration.AppendChild($appSettingsNode)
        $appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created appSettings node:" -ForegroundColor Green
        }

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

if($_.Configuration -eq "appSettings")
{
    $appSettings = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
    $appSettings.Path = “/configuration/appSettings”;

    $appSettings.Name = [system.string]::format(“add[@key=""{0}""]“, $_.Key);
    $appSettings.Value = [system.string]::format(“<add key=”"{0}”" value=”"{1}”" />”, $_.Key, $_.Value);

   
    $appSettings.Sequence = 0
    $appSettings.Owner = “SharePoint”
    $appSettings.Type = 0

    $webapp = Get-SPWebApplication $WebAppUrl
    $webapp.WebConfigModifications.Add($appSettings)
    $webapp.Update()
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created appSettings key:" $_.Key -ForegroundColor Green
}

elseif($_.Configuration -eq "connectionStrings")
{
    $value = $_.Value
    $connectionString = New-Object "Microsoft.SharePoint.Administration.SPWebConfigModification"
    $connectionString.Path = "configuration/connectionStrings"
    $connectionString.Name = "ECConnectionString"
    $connectionString.Sequence = 0 
    $connectionString.Type = 0 
    $connectionString.Owner = "ECConnectionStringOwner"
    $connectionString.Value = $value
    $webapp.WebConfigModifications.Add($connectionString)  #Update the Web Application and apply all existing web.config modifications 
    $webapp.Update() 
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created connectionStrings key:" $_.Key -ForegroundColor Green
}

}# end of second import


Step2: Create batch file to run the script. Save file in .bat format.
cd /d %~dp0
powershell -file ./psUpdateSPWebApp.config.ps1 -WebAppUrl "xxxxx" -WebConfigPath "C:\inetpub\wwwroot\wss\VirtualDirectories\443\web.config"
pause
 

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

Powershell Script - Remove/Delete App to AppCatalog store in SharePoint 2013

The following powershell script will remove app from App catalog and accept following input parameters

1. WebUrl - App Catalog site url
2.AppCatalogName - 'Apps for Sharepoint'
3.AppName - Your .app name

Note: The .app should be in the same directory where you are running the script.

Steps involved
1. Save following script as psRemoveAppFromAppCatalog.ps1


Param(           
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]           
[string]$WebUrl,           
[Parameter(Mandatory=$true)]           
[string]$AppCatalogName,           
[Parameter(Mandatory=$true)]           
[string]$AppName          


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
}

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

try
{
    $site = new-object Microsoft.SharePoint.SPSite($WebUrl)

    $web = $site.openweb()

    $list=$web.Lists[$AppCatalogName]

    $listItems = $list.Items

    $listItemsTotal = $listItems.Count

    Write-Host $listItemsTotal

    if($list -ne $null)
    {
        for ($x=$listItemsTotal-1;$x -ge 0; $x--)
        {
          if($listItems[$x].name -eq $AppName) # file refers to the    name of the document
          {
            $listItems[$x].Delete()
            write-host -f Green "Successssfully unistalled the app -" $AppName " from app catalog" -ForegroundColor Green
          }
        }
    }
}

catch
{
        $Host.UI.RawUI.WindowTitle = " -- Error --"
        Write-Host -ForegroundColor Red $_.ToString()
        Write-Host -ForegroundColor Red $_.Exception.ToString()
}          

Stop-Transcript

Stop-SPAssignment -Global        

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

cd /d %~dp0
powershell -file ./psRemoveAppFromAppCatalog.ps1 -WebUrl "https://catalog.ec.com" -AppCatalogName "Apps for SharePoint" -AppName "Oakton.Solutions.EC.WebApp.app"
pause


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

Powershell Script - Upload App to AppCatalog store in SharePoint 2013

The following powershell script will upload .App file to App catalog and accept following input parameters

1. WebUrl - App Catalog site url
2.AppCatalogName - 'Apps for Sharepoint'
3.AppName - Your .app name

Note: The .app should be in the same directory where you are running the script.

Steps involved
1. Save following script as psUploadAppToCatalog.ps1


Param(           
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]           
[string]$WebUrl,           
[Parameter(Mandatory=$true)]           
[string]$AppCatalogName,           
[Parameter(Mandatory=$true)]           
[string]$AppName          


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
}

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

try
{
    Start-SPAssignment -Global             
    $spWeb = Get-SPWeb -Identity $WebUrl            
    $spWeb.AllowUnsafeUpdates = $true;           
    $List = $spWeb.Lists[$AppCatalogName]           
    $folder = $List.RootFolder
    $FilePath = $currentPhysicalPath + "\" + $AppName    
    #$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
           
    $File= Get-ChildItem $FilePath           
    [Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile("/" + $folder.Url + "/" + $File.Name)           
    $flagConfirm = 'y'           

    #if($spFile.Exists -eq $true)           
    #{           
     #   $flagConfirm = Read-Host "File $AppName already exists in library $DocLibName, do you want to upload a new version(y/n)?"            
    #}           

    #if ($flagConfirm -eq 'y' -or $flagConfirm -eq 'Y')  
    if ($flagConfirm -eq 'y')       
    {           
        $fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()           
        #Add file           
        write-host -NoNewLine -f yellow "Copying file " $File.Name " to " $folder.ServerRelativeUrl "..."           
        [Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($folder.Url + "/" + $File.Name, [System.IO.Stream]$fileStream, $true)           
        write-host -f Green "...Success!"           
        #Close file stream           
        $fileStream.Close()
        write-host -f Green "Successssfully uploaded the app -" $AppName " to app catalog" -ForegroundColor Green     
    }              
$spWeb.AllowUnsafeUpdates = $false;
}

catch
{
        $Host.UI.RawUI.WindowTitle = " -- Error --"
        Write-Host -ForegroundColor Red $_.ToString()
        Write-Host -ForegroundColor Red $_.Exception.ToString()
}
Stop-Transcript         

Stop-SPAssignment -Global
            
Step2: Create batch file to run the script. Save file in .bat format.

cd /d %~dp0
powershell -file ./psUploadAppToCatalog.ps1 -WebUrl "https://catalog.ec.com" -AppCatalogName "Apps for SharePoint" -AppName "xxxxx.app"
pause

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

Powershell Script - Copy files from source location to destination - Xcopy deployment

The following script will backup files from destination location to some other folder and copy files from source location to destination. The script accepts following input parameters

1. Destination location
2. Backup location

Note: I have hard coded source location for convenience, however you can pass as a parameter

Steps involved

1. Save following script as psCopyFiles.ps1


#-----------------------------------------------------------------------------
# Name:             psCopyFiles.ps1 
# Description:      This script will files from source location to destination
#                   location and backup files to another directory
#
# Usage:            Run the script by passing the paramter SourceLocation,
#                   DestinationLocation & BackupLocation
# Created By:       Vamsi Mohan Mitta
# Date:             01/07/2014
#-----------------------------------------------------------------------------


Param([Parameter(Mandatory=$true)]
      [String]
      $DestinationLocation,
      [Parameter(Mandatory=$true)]
      [String]
      $BackupLocation
)
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

#$backupLocation = "\\WIN-K6KO9R0T2LC\C$\Backup"
#$backupFolder = $BackupLocation + "Backup"

if ((Test-Path $BackupLocation) -ne $True)
{
    New-Item $BackupLocation -type directory
    write-host “Successfully created folder!” -ForegroundColor Green
}

else
{
    write-host “Folder already exits” -ForegroundColor Blue
}

#Get current date
#$currentDate = (get-date).tostring("mm_dd_yyyy-hh_mm_s")
$currentDate = Get-Date -format MM-dd-yyyy
if($currentDate -ne $null)
{
    $newFolder = $BackupLocation + $currentDate
    if ((Test-Path $newFolder) -ne $True)
    {
        New-Item $newFolder -type directory
        write-host “Successfully created backup folder-” $newFolder -ForegroundColor Green
    }
    if($newFolder -ne $null)
    {
        $removeBackupFolder = $newFolder + "\*"
        Remove-Item $removeBackupFolder -Recurse

        Copy-Item $DestinationLocation -Destination $newFolder -Recurse
        write-host “Successfully copied files to backup folder-” $newFolder -ForegroundColor Green

        $removeFolder = $DestinationLocation + "*"
        Remove-Item $removeFolder -Recurse
        write-host “Successfully removed files from folder--” $DestinationLocation -ForegroundColor Green

        #copy files from source location to destination
        $sLocation = $currentPhysicalPath + "\webapp.com\*"
        Copy-Item $sLocation -Destination $DestinationLocation -Recurse
        write-host “Successfully copied files & folders to -” $DestinationLocation -ForegroundColor Green
    }   
}

Stop-Transcript
Echo Finish


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

cd /d %~dp0
powershell -file  ./psCopyFiles.ps1 -DestinationLocation "\\WIN-K6KO9R0T2LC\C$\ecwebapp.com\" -BackupLocation "\\WIN-K6KO9R0T2LC\C$\Backup\"
pause

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

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...