Wednesday, July 31, 2013

Get List Items where 'Name' field contains 'x'

This script gets results from list items where name field contains ‘Agenda’.  Also it will create a .csv file where you are running this script. You can see as report when you open this file in the excel.


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

Try
{
#logging (it will create a .csv file where u r running this script)
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "Agenda_Title"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)
$header = "DocumentID;Protocol;Name;ContentType;DocType;URL;Agenda Y/N?"
$header | out-file -FilePath $logfile

$list = $web.Lists["DSMB-SMC Documents"]
$items= $list.items
$time = Get-Date -Format g

$spQuery = New-Object Microsoft.SharePoint.SPQuery
$camlQuery ="<Where><Contains><FieldRef Name='FileLeafRef' /><Value Type='File'>Agenda</Value></Contains></Where>"
$spQuery.Query = $camlQuery
$spQuery.ViewAttributes = "Scope=Recursive";
$spListItems = $list.GetItems($spQuery)

Write-Host "count" $spListItems.count

$count=1
$listurl =$list.ParentWeb.Url
Write-Host "listurl "  $list.ParentWeb.Url
#Write-Host "rrot"  $list.RootFolder.Url
$protocol =$null

    foreach ($item in $spListItems)
            {
           
                   $doctype = $item["DOC TYPE"]
                  if ($item["PROTOCOL"] -ne $null)
                  {
                      $lookup  = [Microsoft.SharePoint.SPFieldLookupValue]$item["PROTOCOL"];  
                      $protocol = $lookup.LookupValue;
                  }
                  else
                  {
                   $protocol = $null
                  }
                 
                $itemurl =    $listurl + "/" + $item.url
                 
                  Write-Host $count  $item.ID $protocol
                  $msg = ("{0};{1};{2};{3};{4};{5};{6}" -f $item.ID,$protocol ,$item.Name,$item.ContentType.Name, $doctype ,$itemurl,"")
                  $msg | out-file -FilePath $logfile  -append
                  $count++
     
                  if($count -eq 6)
                  {
                        #break;
                  }
            }
      }
Catch
      {
            Write-Host "Error occurred while Updating:"  $_  -ForegroundColor Red
          $msg = ( "{0}" -f "Error occurred while Updating:" + $_)
            $msg | out-file -FilePath $logfile  -append
      }


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






No comments:

Post a Comment

Followers