Error You cannot call a method on a null-valued express

When I try to run this script it shows error message

cls
$p = Read-Host "Enter Path"
$regex = "\[([\w|\s*-]+)\]([\w|\s]+(?:\[[\w|\s]+\])?.*)\s*=\s*([\w|,|\s.']+)";
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$pattern = '[^a-zA-Z]'
$studio_ID= Read-Host "Enter Studio Code e.g. SS-"

Get-ChildItem -Recurse -Hidden -LiteralPath $p -Filter *.nfo |
ForEach-Object {
$file = $_.FullName
$name = $_.BaseName

[xml]$fileData = Get-Content -LiteralPath $file;

$tvshow = $fileData.tvshow
$title = $fileData.tvshow.title
$imdb_id = $fileData.tvshow.imdb_id
$newimdb_id = $studio_ID+($title -replace $pattern,'')

if(-not $tvshow.zap2itid )
{
$childElement = $fileData.CreateElement("zap2itid")
$newXmlElement = $tvshow.AppendChild($childElement)
#$newXmlElement.InnerText = $newimdb_id
}

if( ($imdb_id -ne $newimdb_id) -and $name -eq "tvshow" )
{
Remove-Item $file -Force

$fileData.tvshow.imdb_id = $newimdb_id
$fileData.Save($file)
$_.Attributes ="Hidden"

Write-Host "File Update: $file"
}else{
#Write-Host "File Already correct: $name"
}
}

Above code works but it shows a error message

You cannot call a method on a null-valued expression.
At Update_IMDB_id.ps1:24 char:13

  • $newXmlElement = $tvshow.AppendChild($childElement)
  • CategoryInfo : InvalidOperation: (:slight_smile: , RuntimeException
  • FullyQualifiedErrorId : InvokeMethodOnNull

Make sure $fileData.tvshow is returning an object. You can VSCode or ISE to debug by putting a break point or atleast try to print $fileData.tvshow to make sure it returns a valid object.

If $fileData.tvshow returns null, then $tvshow variable becomes null and a null value wont have a method to get called.