3

I am trying to run the following PowerShell script in order to fill-in the values of the title column with the values from the esubject column:

$site = new-object Microsoft.SharePoint.SPSite(“http://servername/sites/contoso”)
$web =  Get-SPWeb -Identity http://servername/sites/contoso
$lista =$web.Lists["somelist"]
$items = $lista.items

foreach ($item in $items) {
  $user = $item["esubject"]
  $item["title"] = $user
  write-host $user
  $item.update()
}

$lista.update()

However I am getting the following error:

enter image description here

Any pointers as to why this is happening?

3

I think you should check on 2 things

  1. In $item["title"] you should use casing, because SharePoint understands Title hence improve it to $item["Title"].
  2. I guess you don't need $lista.update()

Refer below updated code.

#Add SharePoint PowerShell Snapin which adds SharePoint specific cmdlets
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue

#Variables that we are going to use for list editing
$listName = "somelist"

#Get the SPWeb object and save it to a variable
$web = Get-SPWeb http://servername/sites/contoso

#Get the SPList object to retrieve the "Demo List"
$list = $web.Lists[$listName]


#Get all items in this list and save them to a variable
$items = $list.items

#Go through all items
foreach($item in $items)
{
    $user = $item["esubject"]
    #Change the value of the "Title" column
    $item["Title"] = $user

    #Update the item
    $item.Update()

}
2

It's because $lista is $null. Are you sure this is correct title of the list?

In PowerShell you won't get error when you try load list with incorrect title. You also won't get exception executing follofing:

$null.Something
foreach ($a in $null) {}

That's why you get an exception so late, on the Update() method.

You should also use Get-SPSite instead of object constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.