0

I have a script that is supposed to go into a list and find a replace values with a different value in a column. The error I get is 'You cannot call a method on null-valued expression' pointing to this line ($oldurl.URL = $oldurl.URL.Replace("T9", "DR"))

Any idea what's wrong?

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$siteUrl = "https://[siteName]"

$webName = “Resources”

$listName = "Training"

$spSite = new-object Microsoft.SharePoint.SPSite($siteurl)

$spWeb = $spSite.OpenWeb($webName)

$spList = $spWeb.Lists[$listName]

Write-Host("URL: [$spList]")

foreach($Item in $spList.Items )

{

$oldurl = new-object Microsoft.SharePoint.SPFieldUrlValue($Item["INUM"])

$oldurl.URL = $oldurl.URL.Replace("T9", "DR")

Write-Host("URL: [$oldurl]")

$Item.Update()

}

$spWeb.Dispose()

2 Answers 2

0

Looks like the $Item["INUM"] doesn't have a value at the first retrived item, so the $oldurl is NULL! and you can't use the replace function with a NULL string

So you should check if the $oldurl is not null before calling the replace function as the following:

foreach($Item in $spList.Items)
{
$oldurl = New-Object Microsoft.SharePoint.Client.FieldUrlValue($Item["INUM"])
if ($oldur -eq $null)
{continue}
else
{
  $oldurl.URL = $oldurl.URL.Replace("T9", "DR")
  Write-Host("URL: [$oldurl]")
  $Item.Update()
}

}

or

foreach($Item in $spList.Items)
{
$oldurl = New-Object Microsoft.SharePoint.Client.FieldUrlValue($Item["INUM"])
if ($oldur -ne $null)

{
  $oldurl.URL = $oldurl.URL.Replace("T9", "DR")
  Write-Host("URL: [$oldurl]")
  $Item.Update()
}
 else continue

}
0

As Mohamed said, you could add a judgment statement to avoid the null value exception, and you need to re-assign the modified value to item.

foreach($Item in $spList.Items)
{
$oldurl = New-Object Microsoft.SharePoint.SPFieldUrlValue($Item["INUM"])
if ($oldur -ne $null)

{
  $oldurl.URL = $oldurl.URL.Replace("T9", "DR")
  Write-Host("URL: [$oldurl]")
$Item["INUM"]= [Microsoft.SharePoint.SPFieldUrlValue]$oldurl
  $Item.Update()
}
 else continue

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.