Add List Items of different type by powershell

17/12/2012 12:20

There are several field types in Sharepoint 2010 and each of them is filled in different way. Here are some examples:

$spWeb = Get-SPWeb -Identity "http//server/sitecollection"
$spWeb.AllowUnsafeUpdates=$true
$spList = $spWeb.Lists["My List"]

$spListItem = $spList.AddItem()


#Single line of text
$spListItem["Title"] = "Dog"


#type URL - Hyperlink

    $field=new-object Microsoft.Sharepoint.SPFieldUrlValue
    $field.Url = "https://www.google.com"
    $field.Description="My favorite link"
    $spListItem["CustomURLfield"]=$field
  
#type Image

 $image = new-object Microsoft.SharePoint.Publishing.Fields.ImageFieldValue
 $image.ImageUrl = "https://server/sitecollection/publishingimages/image1.jpg"
 $spListItem["CustomImage"]=$image

 

#type Lookup (ID + ; + # + value in lookup list)
 $spListItem["LinkedAuthor"]="2;#My Second Author"

 

#type MultiLookup
 $spListItem["LinkedAuthors"]="2;#My Second Author;#;4;#My Fourth Author;#;1;#My First Author"

 

#type DateTime
  $spListItem["ArticleDate"]=[dateTime]"10/12/2011"

 

#type User

    $userName = "domain\testuserName"
    $user = $spWeb.EnsureUser($userName)
    if($user)
    {
                $spListItem["YourUserColumnInternalName"] = $user
    }


$spListItem.Update()

 

#type Attachment

     #Get newly created item id (after update)
     $id = $spListItem["ID"]
     $filePath = "c:\temp\file.jpg"
     $bytes = [System.IO.File]::ReadAllBytes($filePath)
     $item = $spList.GetItemById($id)
     $item.Attachments.Add([System.IO.Path]::GetFileName($filePath), $bytes)
     $item.Update()