Thursday, February 12, 2015

Powershell to update multiple items with specific condition

Scenario:
Client wanted to restructure the data and wanted to update all the items in a list with particular value to a new value.

Solution:
Quick PS script did the magic

Code:

cls

#Load SharePoint Snap In
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function xUpdateAll-SPItems
{  
 param ($Url, $ListName,$ColumnName,$OldValue,$NewValue) 

$web = Get-SPWeb $Url 
$list = $web.Lists.TryGetList($ListName)

$items = $list.Items
foreach ($item in $items)
{
    $existingValue  = $item[$ColumnName]
    If($existingValue -eq $OldValue)
    {  
       Write-Host "Updating item : " + $item.ID      
     
        $item[$ColumnName] = $NewValue
        $item.Update()     
     }     
}  

 $web.Dispose()
 Write-Host "Updated all items successfully" -foregroundcolor Green  
 
}


#$url=Read-Host "Enter site url"
#$listName=Read-Host "Enter list library name"
#$columnName=Read-Host "Enter column name"
#$oldValue=Read-Host "Enter old value"
#$newValue=Read-Host "Enter new value"

$url="http://server:37788"
$listName="mylist"
$columnName="Column Name"
$oldValue="Bad Value"
$newValue="Other"


xUpdateAll-SPItems $url $listName $columnName $oldValue $newValue

Article:

0 comments: