Friday 7 November 2014

Replace URLs placed in the SharePoint list items by using PowerShell

The scripts are used to find the specified URLand replace with the new URL in the SharePoint list items.

 ReplaceURL.ps1

Param($WebAppUrl,$ListName,$OriginalValue,$ValueToReplace);
Add-PSSnapin Microsoft.SharePoint.PowerShell

function Main($WebAppUrl,$ListName,$OriginalValue,$ValueToReplace)
{
Write-Host -Fore Green "Starting..."

write-host "Web Application URL: " $WebAppUrl
write-host "List Name: " $ListName
write-host "Original value:" $OriginalValue
write-host "Value to Replace:" $ValueToReplace      


$SPWebApp = Get-SPWebApplication $WebAppUrl
foreach ($SPSite in $SPWebApp.Sites)
{
if ($SPSite -ne $null)
{
Write-Host -Fore Green *****************************************
Write-Host -Fore Green "Web Url - " $SPSite.RootWeb.Url

#Get the SPWeb object which holds the list
$web = $SPSite.RootWeb
$web.AllowUnsafeUpdates = $true;    
#Get the list
$list = $web.Lists[$ListName]

if ($list -ne $null)
{

#Create the query to use for paging through the items.
$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewAttributes = "Scope='Recursive'";
$spQuery.RowLimit = 5000
$caml = '<OrderBy Override="TRUE"><FieldRef Name="ID"/></OrderBy>'
$spQuery.Query = $caml
#Loop through all items and process them.
do
{
$listItems = $list.GetItems($spQuery)
$spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach($item in $listItems)
{
foreach ($field in $list.Fields) #Get all fields in lists
{
#Write-Host -Fore Green "Field Name -" $field.Title "Field Type -" $field.Type

if($field.Type -eq "Text" -or $field.Type -eq "Note" -or $field.Type -eq "URL")
{
$value =$item[$field.InternalName];

if($value -ne $null -and $value.Contains($OriginalValue))
{            
  $item[$field.InternalName] = $value.Replace($OriginalValue, $ValueToReplace)                
  $item.Update()  
}
}
}
Write-Host -Fore Green "Item ID - " $item.ID.tostring() "Updated!"
  }
}
while ($spQuery.ListItemCollectionPosition -ne $null)
}
else
{
Write-Host -Fore Green "Microfeed list not exist.."
}

$web.AllowUnsafeUpdates = $false;
$web.Dispose()
}
}
   
    Write-Host -Fore Green "End..."
}

Start-Transcript

Main $WebAppUrl $ListName $OriginalValue $ValueToReplace
Stop-Transcript

ReplaceURL.bat

echo off

cd %SystemRoot%\system32\WindowsPowerShell\v1.0
powershell {Set-ExecutionPolicy Unrestricted}
cd /d %~dp0

SET WebAppUrl="http://d.mysite.hot.tognum.com/"
SET ListName="MicroFeed"
SET OriginalValue="https://"
SET ValueToReplace="http://"

powershell.exe -command .\ReplaceURL.ps1 '%WebAppUrl%' '%ListName%' '%OriginalValue%' '%ValueToReplace%'
powershell {Set-ExecutionPolicy Restricted}
pause




No comments:

Post a Comment