Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Friday, August 16, 2013

Create SharePoint Choice Field (Site Column) using PowerShell

Start-SPAssignment -Global
$url = "siteurl"
$web = get-spweb $url

$fieldName = "Surya"
$field = $web.Fields[$fieldName]

 if($field -ne $nul)
 {
      Write-Host $field.Title "Field already avilable in the site"
 }
 else
 {

#There are 2 ways to create a field.
#First Apporach
 <#
      Write-Host "no fields exist with this name. creating..."
      $web.fields.add($fieldName, "Choice", $true)
      $field = $web.fields.getfield($fieldName)
      $field.Group = "Custom Columns"
      $field.Choices.Add("Yes")
      $field.Choices.Add("No")
      $field.Update()
     Write-Host "Field Created"
#>

#Second Apporach

      $suryafield = "<Field Type='Choice' DisplayName='Surya' Required='TRUE' Format='Dropdown' Group='Custom Columns'
      FillInChoice='FALSE' StaticName='Surya' Name='Surya'>
            <CHOICES>
                <CHOICE>YES</CHOICE>
                <CHOICE>NO</CHOICE>
            </CHOICES>
           </Field>"
      $web.Fields.AddFieldAsXml($suryafield)
  Write-Host "Field Created"
 }

 Stop-SPAssignment -Global


Wednesday, August 14, 2013

Create Content Types and Fields using Powershell

 Below script will work for

1.       1. Add Content Types to the web site
a.       Create a Content Type
b.      Add fields to Content Type
c.       Modify existing fields of  Content Type
d.      Delete fields from Content Type
e.      Create a new field and then add to the content type
2.       2. Add Content Type to the SharePoint List
3.       3. Sorting Content Types in the List

I referred below posts



Start-SPAssignment -Global

function  Sort-ContentTypes(
       [Microsoft.SharePoint.SPList]$list) {

         Write-Host $list.Title
$rootFolder = $list.RootFolder
$DefaultContentTypeName = "Document"  #setting "Document" as default content type.

 $rootFolder.UniqueContentTypeOrder = $null
 $rootFolder.Update()

#Get content types fromt the button
$contentTypesInPlace = New-Object 'System.Collections.Generic.List[Microsoft.SharePoint.SPContentType]'
$contentTypesInPlace = $rootFolder.ContentTypeOrder
 
#Has a default content type name been specified?
      if ($DefaultContentTypeName)
      {
            $contentType = $contentTypesInPlace | where { $_.Name -eq $DefaultContentTypeName }
            if ($contentType -ne $null)
            {
                  #Add the default content type
                  $sortedListOfContentTypes = New-Object 'System.Collections.Generic.List[Microsoft.SharePoint.SPContentType]'
                  $sortedListOfContentTypes += $list.ContentTypes[$DefaultContentTypeName]
                   
                  #Remove the default content type from the list
                  $contentTypesInPlace = $contentTypesInPlace | where {$_.Name -ne $DefaultContentTypeName}
            }
            else
            {
                  Write-Error "$DefaultContentTypeName was not found in the list, sorting by Name alone"
            }
      }
      else
      {
            Write-host "No default content type specified"
      }
       
      #sort the remaining content types and add the sorted list
      foreach ($contentType in $($contentTypesInPlace | Sort-Object -Property Name ))
      {
      #Add the content types
            $sortedListOfContentTypes = [Microsoft.SharePoint.SPContentType[]] $sortedListOfContentTypes + $contentType
      }

      $rootFolder.UniqueContentTypeOrder = [Microsoft.SharePoint.SPContentType[]] $sortedListOfContentTypes
       
      #Update the root folder
      $rootFolder.Update()
      Write-host "ContentType(s) sorted and added to the dropdownlist in list $($list.Name)"
     
 }



$url = "http://spdev5:8002/sites/library"
$web = get-spweb $url

#The Display Name of the Content Type
$ctypeName = "SuryaCT1"

try{

if($web.availablecontenttypes[$ctypeName] -eq $null)
{
      $ctypeParent = $web.availablecontenttypes["Document"]
      $ctypeTest = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
      ##group name
      $ctypeTest.Group = "Custom Group"
      $web.contenttypes.add($ctypeTest)
     
#     $ctypeTest = $web.ContentTypes[$ctypeName]
     
      Write-Host "ctypeAgenda" $ctypeTest.id
     
      ##Add fields to the ContentType

      $field = $web.fields.getfield("Field1")
     
      if($ctypeTest.Fields["Field1"] -eq $null)
      {
            $fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
            $ctypeTest.fieldlinks.add($fieldLink)
      }
     
      ##Update existing fields - as Required
      if($ctypeTest.Fields["Field2"] -ne $null)
      {
            $field = $ctypeTest.Fields["Field2"]
            $ctypeTest.FieldLinks[$field.Id].Required=$true
      }
       
     
      ##Delete fields from  ContentType
           
      if($ctypeTest.Fields["Field3"] -ne $null)
      {
         Write-Host "Field2"
        $field = $ctypeTest.Fields["Field3"]
        $fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
        $ctypeTest.FieldLinks.Delete($fieldLink.id);
      }
     
      ##create new field and then add to the ContentType
       
      $web.fields.add("SuryaField", "Text", $false)
      $field = $web.fields.getfield("SuryaField")
      $field.Group = "Custom Columns"
      $fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
      $ctypeTest.fieldlinks.add($fieldLink)


      $ctypeTest.Update($true)
       
}
else
{
      Write-Host $ctypeTest " Contentype is already avilable in the site."
}

#$ctypeTest = $web.ContentTypes[$ctypeName]
## Add ContentType to the SharePoint List
      if($ctypeTest -ne $null)
            {
           
            $list =  $web.Lists.TryGetList("suryadocs")
           
            if($list.ContentTypesEnabled -eq $false   )
            {
            $list.ContentTypesEnabled = $true;
                  $list.Update()
            }
             
              if ($list.ContentTypes[$ctypeTest.Name] -eq $null)
             {
               $list.ContentTypes.Add($ctypeTest);
                   Write-Host $ctypeTest.name " ContentType added"
                   Sort-ContentTypes $list
             }
            }
}
catch
{
      Write-Host "Error occurred while Updating:"  $_  -ForegroundColor Red
}

Stop-SPAssignment –Global



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()






Followers