Search This Blog

Wednesday 30 May 2012

Create Field and update List Item in SharePoint 2010 using PowerShell


Hi All,
Recently I had a situation to add a new field in an existing SharePoint Lists and update value to the newly added field for existing list items using power shell.
Then I created the following power shell script to achieve my requirement.

Script:
try
{
    $SPSite = New-Object Microsoft.SharePoint.SPSite("http://chesgh201tw1v:1605")
    $SPWeb = $SPSite.OpenWeb()
    $List = $SPWeb.Lists.TryGetList("Document Type Master")
    if($List -ne $Null)
    {
        $List.Fields.Add("DisplayOrder",[Microsoft.SharePoint.SPFieldType]::Number,$false)
        $List.Update()
        write-host "New Field Added in List" -foregroundcolor Green
       
        $ListView = $List.Views["All Items"];
        if($ListView -ne $Null)
        {
            $ListView.ViewFields.Add("DisplayOrder");
            $ListView.Update();
        }
        write-host "Field added in default View" -foregroundcolor Green
       
        $SPListItemCollection = $List.Items
        if($SPListItemCollection.Count -gt 0)
        {
            #Get list item collection
            $spListItemsCount = $SPListItemCollection.Count    #Get list items total count
            write-host "Updating values in the newly added field" -foregroundcolor Green
            for($Counter = $spListItemsCount-1; $Counter -ge 0; $Counter--)
            {
                $spListItem = $SPListItemCollection[$Counter]    #Get list item via index
                $Title = $spListItem["Title"]
                switch ($Title)
                    {
                        "Policy"
                        {
                            $spListItem["DisplayOrder"] = 1
                        }
                        "Script"
                        {
                            $spListItem["DisplayOrder"] = 2
                        }
                        "Job Aid"
                        {
                            $spListItem["DisplayOrder"] = 3
                        }
                        "Talking Points"
                        {
                            $spListItem["DisplayOrder"] = 4
                        }
                   }
               
                $spListItem.Update()
            }
            write-host "Value(s) updated successfully in the newly added field" -foregroundcolor Green
        }
        write-host "Operation completed successfully" -foregroundcolor Green
    }
    else
    {
        write-host "List is not found" -foregroundcolor Red
    }

}
catch [System.SystemException]
{
    write-host “Execution stopped due to: “+$_.Message -foregroundcolor Red
}

Result:














Done.  I have achieved that, now the new field added in SharePoint list and values updated in the field accordingly.

Happy Scripting ...........................................

No comments:

Post a Comment