Interview Questions administrator

Best SharePoint administrator Interview Questions and Answers with topic wise:


Recycle Bin | MMS | ManagedVsCrawledProperties |

Thursday, June 19, 2014

How To: Create new field and add items in SharePoint list using PowerShell


Below code will help us on below scenerios:
  1. Create a new list in SharePoint using powershell
  2. Check whether the list exits or not?
  3. Create a new field in SharePoint list using powershell
  4. Add items to the list in SharePoint using powershell?


Please correct the syntax as below for the scripts.
e.g:  Replace displayname=""+ $DisplayName +"" to DisplayName='"+ $DisplayName +"' 
==================================================================================

$siteURL= "your site URL"

$ListName ="List Name"

==================================================================================

$docSite = new-object Microsoft.SharePoint.SPSite($siteURL)
$docWeb = $docSite.OpenWeb()

$TemplateType = $docWeb.ListTemplates["Custom List"]

function Create-SPList([string]$listName, [string]$description)
{
 $exLst = $docWeb.Lists[$listName]

        //Create new list if already doesn't exists
 if($exLst -eq $null)
 {
  Write-Host "`n List does not exist. Creating $listName list`n"
  [void]$docWeb.Lists.Add($listName, $description, $TemplateType)
  $docWeb.Update()
 }  
}

==================================================================================

function Add-SPSingleLineOfTextField([string]$listName, [string]$DisplayName, [string]$Name, [string]$Required, [string]$DateType)
{
  $OpenList = $docWeb.Lists[$listName]
  $firstNameColXml = "" 
  $OpenList.Fields.AddFieldAsXml($firstNameColXml,$true, 
  [Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView) 
}

function Add-SPListItems([string]$listName, [string]$Name, [string]$Value)
{
  $OpenList = $docWeb.Lists[$listName]   
  $newItem = $OpenList.items.add()
  $newitem["Title"] = $Name 
  $newitem["Value"] = $Value   
  $newitem.update()
}

==================================================================================

//To create a new list name
Write-Host "`n create $ListName list `n"
Create-SPList -listName  $ListName   -description "List Description"

//To create a new field name in list
Write-Host "`n Adding fields to the $ListName list `n"
Add-SPSingleLineOfTextField -listName $ListName -Name Value -DisplayName Value -Required FALSE

//To add items to the list
Write-Host "`n Adding items to the $ListName list `n"
Add-SPListItems -listName $ListName -Name "Name1" -Value "Value1"
Add-SPListItems -listName $ListName -Name "Name2" -Value "Value2"

===================================================================================

Please let me know if faced any issues while using the above scripts and provide your valuable feedback

Thanks,
Sasi Kumar Reddy

No comments:

Post a Comment