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

Welcome Forums General PowerShell Q&A Error You cannot call a method on a null-valued express

Viewing 1 reply thread
  • Author
    Posts
    • #238712
      Participant
      Topics: 7
      Replies: 9
      Points: 53
      Rank: Member

      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: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      • This topic was modified 1 week, 5 days ago by kvprasoon. Reason: code formatting
    • #240101
      Senior Moderator
      Topics: 9
      Replies: 1244
      Points: 4,480
      Helping Hand
      Rank: Community Hero

      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.

      • This reply was modified 1 week, 5 days ago by kvprasoon. Reason: post correction
Viewing 1 reply thread
  • You must be logged in to reply to this topic.