Forum Discussion

Brent Ellis's avatar
Brent Ellis
Silver Contributor
Mar 13, 2017

PnP PowerShell - tell if an Add-PnPFile was successful

What is the best way in powershell scripts to tell if an Add-PnPFile was actually successful in performing an upload?  Ideally want to store a "successful" true or false in a variable.

4 Replies

  • Gary Schultz's avatar
    Gary Schultz
    Iron Contributor

    The following works for me

     

    $FileSuccessLog = "C:\temp\logging\FileSuccessLog.log"
    $FileFailureLog = "C:\temp\logging\FileFailureLog.log"

    Try{
      Add-PNPFile -Path $FilePath -folder "Some Document Library/Folder"
      $fileSuccess = "Y"
    }
    Catch{
      $fileSuccess = "N"
    }
    Finally {
      Switch($fileSuccess){
        N{
          Add-content $FileFailureLog -value "$(get-date -f o) Failure with attempt to add file $FilePath."
        }
        Y{
          Add-content $FileSuccessLog -value "$(get-date -f o) Success with attempt to add file $FilePath."
        }
      }
    }

  • Check if you can do something similar to the below.

     

    $status=Add-PnPFile -Folder "Shared documents" -Path C:\eports.xml -ErrorAction SilentlyContinue
    If($status)
    {
    $successful=$true
    }
    Else
    {
    $successful=$false
    }
    • Brent Ellis's avatar
      Brent Ellis
      Silver Contributor

      Kinda yes kinda no

       

      For example, in this example, a library called "Shared documents bad name" doesnt exist, but $successful is true.

      $status=Add-PnPFile -Folder "Shared documents bad name" -Path C:\eports.xml -ErrorAction SilentlyContinue
      If($status)
      {
      $successful=$true
      }
      Else
      {
      $successful=$false
      }

      I trust in general it will work if I have my folder parameter and path parameter correct, but I typically have had several try catchs in my "manual" upload functions that would account for various things, and would always return the document ID of the newly updated file.

       

      We do alot of deleting files off of file shares after they have uploaded, but I can't figure out a true way to confirm the file was ACTUALLY uploaded without making a second call I guess to confirm the file with the file name exists.  Often these files will overwrite existing ones though.

       

      • Brent Ellis's avatar
        Brent Ellis
        Silver Contributor

        Ok, I've got it now, I can use this:

         

            $upload = Add-PnPFile -Path $file.FullName -Folder "Shared Documents" -Values $metadata
            if($upload.UniqueId){
                $successCounter += 1
                Write-Host "Successful Upload" -ForegroundColor Green
                Remove-Item -LiteralPath $file.FullName   
            } else {
                Write-Host "ERROR - Unable to Upload" -ForegroundColor Green
            }

        $upload itself isnt null if failed, but $upload.UniqueId would be null if failed.

Resources