none
Null value error RRS feed

  • Question

  • Here is my code and the error I am getting. How do I avoid the null value error by testing for a .pdf file prior to the rename?

    Error:You cannot call a method on a null-valued expression.
    At C:\Users\casj03\Desktop\PDF_MOVE_COMPRESSION.ps1:21 char:45
    +                     $zipfile = $name.Replace <<<< (".pdf",".zip")
        + CategoryInfo          : InvalidOperation: (Replace:String) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull

    $filePath = "\\jcc.jccsystems.com\omafiles\SPC-ProductionDatabases\Mailstream\Archive" 
    $pdf = Get-ChildItem -Recurse -Path $filePath | Where-Object { $_.Extension -eq ".pdf" } 
     
    ########### END of VARABLES 
      
    foreach ($file in $pdf) { 
                        $name = $file.name 
                        $directory = $file.DirectoryName 
                        $zipfile = $name.Replace(".pdf",".zip") 
                        sz a -tzip "$directory\$zipfile" "$directory\$name"
                        }



    • Edited by goosebags Tuesday, July 8, 2014 8:04 PM
    Tuesday, July 8, 2014 7:59 PM

Answers

All replies

  • You should spend some time learning PowerShell;

    Try this:

    $filePath='\\jcc.jccsystems.com\omafiles\SPC-ProductionDatabases\Mailstream\Archive\*'
    
    Get-ChildItem -Recurse -Path $filePath -Include *.pdf | 
        ForEach-Object{
             $zipfile=$_.Fullname.Replace('.pdf','.zip') 
             sz a -tzip $zipfile $_.Fullname
         }


    ¯\_(ツ)_/¯

    • Proposed as answer by Mike Laughlin Tuesday, July 8, 2014 8:07 PM
    Tuesday, July 8, 2014 8:06 PM
  • Hi,

    Try it this way:

    foreach ($file in $pdf) { 
        If ($file) {
            $name = $file.name 
            $directory = $file.DirectoryName 
            $zipfile = $name.Replace(".pdf",".zip") 
            sz a -tzip "$directory\$zipfile" "$directory\$name"
        }
    }


    EDIT: See above.

    Don't retire TechNet! - (Don't give up yet - 12,950+ strong and growing)

    • Edited by Mike Laughlin Tuesday, July 8, 2014 8:07 PM
    • Marked as answer by goosebags Tuesday, July 8, 2014 9:00 PM
    Tuesday, July 8, 2014 8:06 PM
  • Thank you very much for the help! Worked very well.
    Tuesday, July 8, 2014 9:01 PM