Thursday, July 25, 2013

Read List Items using Client Object Model JavaScript SharePoint 2010

Below script reads announcements items and shows in the alert box.

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

Add below script here or add a content editor webpart to your page and include the script

</asp:Content>

    
 <script type="text/javascript">

     ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
     // jQuery(document).ready(function(){
     //        ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
     //   });

     function retrieveListItems() {

         var clientContext = new SP.ClientContext.get_current();
         var oList = clientContext.get_web().get_lists().getByTitle('Announcements');

         var camlQuery = new SP.CamlQuery();
         camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
         this.collListItem = oList.getItems(camlQuery);

         clientContext.load(collListItem);

         clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

     }

     function onQuerySucceeded(sender, args) {
         alert('sucess');
         var listItemInfo = '';

         var listItemEnumerator = collListItem.getEnumerator();

         while (listItemEnumerator.moveNext()) {
             var oListItem = listItemEnumerator.get_current();
             listItemInfo += '\nID: ' + oListItem.get_id() +
            '\nTitle: ' + oListItem.get_item('Title') +
            '\nBody: ' + oListItem.get_item('Body');
         }

         alert(listItemInfo.toString());
     }

     function onQueryFailed(sender, args) {

         alert('fail');
         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
     }</script>





Friday, July 19, 2013

Get SharePoint 2010 Lookup field value for a list item using Powershell


    foreach ($item in $spListItems)
            {
                  if ($item["lookupcol"] -ne $null)
                  {
                      $lookup  = [Microsoft.SharePoint.SPFieldLookupValue]$item["lookupcol"];  
                      $lookupvalue = $lookup.LookupValue;
                        Write-Host "lookupcol value" $lookupvalue
                  }
                   

            }

Wednesday, July 17, 2013

SharePoint SPFieldChoice change selected value Powershell

I have a dropdownlist with below items

Item1
Item2
Item3
Item4

When you run below script it will update dropdown list selected value as "Item4" for all sharepoint list items.


            foreach ($item in $items)
            {
           
             $field = [Microsoft.SharePoint.SPFieldChoice]$item.Fields["DOC GROUP"];
             # Write-Host "ID" $field.id
             write-host "Choice Field:" $item.url  $field.Choices[3]
             $item["DOC GROUP"] =  $field.Choices[3]
             $item.SystemUpdate()  

#foreach ($str in $field.Choices)
                #{
                 #  Write-Host  $str;

               # }
            }
                                

Tuesday, July 16, 2013

Batch Update SharePoint List Items using Powershell

$URL = "http://spdev5:8002/"
$site = New-Object Microsoft.SharePoint.SPSite($URL)
$web = $site.openweb("")


#logging (it will create a .csv file where u r running this script)
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "CopyName2Title"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)

$header = "S.No,Message"
$header | out-file -FilePath $logfile

$count=1



# New-Object
#$strPost =New-Object  System.Text.StringBuilder
$methodBuilder=New-Object  System.Text.StringBuilder

$list = $web.Lists["Current Studies Test"]
$items= $list.items
$guid = $list.ID
$strGuid = $guid.ToString()
$title="surya"
 $time = Get-Date -Format g

Write-Host  "Start Time " $time

#Write-Host "count" $items.count   
$strPost = "<?xml version=""1.0"" encoding=""UTF-8""?><ows:Batch OnError=""Return"">"
   foreach($item in $items)
   {
         $strPost += "<Method>"
        $strPost +=  "<SetList Scope=""Request"">" + $strGuid +"</SetList>"
      $strPost += "<SetVar Name=""ID"">"+ $item.ID +"</SetVar>"
      $strPost += "<SetVar Name=""Cmd"">Save</SetVar>"
        $strPost += "<SetVar Name=""owsfileref"">" + $item.File.ServerRelativeUrl + "</SetVar>"
      $strPost += "<SetVar Name=""urn:schemas-microsoft-com:office:office#Title"">" + $title +"</SetVar>"
        $strPost += "</Method>"
     
      $msg = ("{0},{1}" -f $count, "URL:" + $item.url)
      $msg | out-file -FilePath $logfile  -append
    
       $count++
       Write-Host       $count

     #if($count -eq 2000)
       #{
           
             $strPost += "</ows:Batch>"
     
              #Write-Host $strPost
             $strProcessBatch = $web.ProcessBatchData($strPost)
           
             Write-Host  "Updated at:" $time
            $msg = ("{0},{1}" -f $count, "Updated:" + $time)
            $msg | out-file -FilePath $logfile  -append
  
           
      # }


  }
 
 $web.Dispose()
$site.Dispose()

You can see related posts as well with c# and powershell

Wednesday, July 10, 2013

Copy 'Name' field as is to the 'Title' Field SharePoint 2010 Document library

When you run below script it will update the 'name' field as is to the 'Title' for all existing files in the document library.
dont forget to change your list name

Auto Fill Title of Document in Document Library in SharePoint 2010



$URL = "http://spdev5:8002/sites/library"
$site = New-Object Microsoft.SharePoint.SPSite($URL)
$web = $site.openweb("")


#logging (it will create a .csv file where u r running this script)
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "CopyName2Title"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)

$header = "S.No,Message"
$header | out-file -FilePath $logfile

$count=1
$fieldname="Title"
     
      foreach($list in $web.Lists)
      {
      if($list.BaseType -eq "DocumentLibrary")
        {
            $listname = $list.title
            if($list.title -eq "your list name") # update with your list name. if u remove this condition then it will apply to all libraires. 
            {
                  Write-Host $list.title
                  $msg = ("{0},{1}" -f "List:", "=========================== $listname ======================")
               $msg | out-file -FilePath $logfile  -append
           foreach($item in $list.items)
             {
                  $item[$fieldname] = $item["Name"]
                  $item.SystemUpdate();
                 
                  Write-Host $count". FileName:"   $item.url
                  $msg = ("{0},{1}" -f $count, "URL:" + $item.url)
                  $msg | out-file -FilePath $logfile  -append
                  $count++
              }
                  # $list.update()
         }
      }
   }
$web.Dispose()
$site.Dispose()

Tuesday, July 9, 2013

Check Column exist in SharePoint List using Powershell

Sometimes when we are working with SharePoint list items will get an error like

Column has been deleted by another user or not exist.

for this we can use below code to check column exist or not

 foreach($list in $web.Lists)
      {
         if($list.BaseType -eq "DocumentLibrary")
         {
              if( $list.Fields.ContainsField("ddlTest") -eq $true)
               {                                       
               Write-Host "found" $list.title
               }
               else
               {
                #  Write-Host "not found"  
               }
         }
      }

Monday, July 8, 2013

ArryaList in Powershell

$fieldsArray = $null
$fieldsArray = New-Object 'System.Collections.Generic.List[string]';
$fieldsArray.Add("DSMB-SMC Documents1")
$fieldsArray.Add("DSMB-SMC Documents2")
$fieldsArray.Add("DSMB-SMC Documents3")
     
 Write-Host "count" $fieldsArray.count
 foreach($fieldLink in $fieldsArray){
       Write-Host    $fieldLink
      }
       

              

Followers