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"
}

}

No comments:

Post a Comment