Search code examples
powershellsharepointfile-uploadsharepoint-onlinelast-modified

How to retrieve files from a Sharepoint Folder with metadata(column) to check wether the file exists or not?


I am looking to upload the file to SharePoint using Add-PnPFile, but it overwrites the file every time. I want to check if the file exists or not ? If yes then if it is modified in the last day or not ? If yes then i will upload the file(overwrite the existing file using add-pnpfile) else I skip the file and check for the next file ?

Is there anyway ?

#install and import module
Import-Module SharePointPnPPowerShellOnline 

#Get Connection to the url
Connect-PnPOnline "Some SharePoint Url" -UseWebLogin

#get the files from a local folder
$Files = Get-ChildItem "C:\Some Local FolderPath" -Recurse

#Now check wether the file is being modified or not ? 
foreach($File in $Files){
    
#Logic to check if the file exists in the sharepoint folder or not ? If it exist then i want to check wether it is being modified or not ? if yes then i will add the file
#if not then i will skip that file and check for other files.
        
        #Calculating LastWritetime for the file.
        $LastWriteTimeForThisFile = $File.LastWriteTime.Day
        $difference = (Get-Date).Day - $LastWriteTimeForThisFile
    
        if(file exists ? then check the difference in Lastmodified dates)
        if ( $difference -lt 1) 
        {
         
         $upload = Add-PnPFile -Path $File.FullName -Folder $SharePointFolderPath
         $message = "Successfully Uploaded"  #this i will be having an entry in log file.
        }
        else{
         $message = Not Modified so not uploading again #this i will be having an entry in log file.
        }
    }


Solution

  • You could try the following, it should work for you.

    foreach($File in $Files){
        #Calculating LastWritetime for the file.
        $LastWriteTimeForThisFile = $File.LastWriteTime
        $difference = (Get-Date) - $LastWriteTimeForThisFile
        
        #Check if File exists Already
        $fileURL= $SharePointFolderPath+"/"+$file.name
    
        $FileExists = Get-PnPFile -Url $fileURL -ErrorAction SilentlyContinue
        
        if($FileExists){
            if ( $difference.days -lt 1) {         
             $upload = Add-PnPFile -Path $File.FullName -Folder $SharePointFolderPath
             $message = "Successfully Uploaded"  #this i will be having an entry in log file.
            }
            else{
             $message = Not Modified so not uploading again #this i will be having an entry in log file.
            }
        }
        #If File doesnot exist, upload the file.
        Else{
            $upload = Add-PnPFile -Path $File.FullName -Folder $SharePointFolderPath
            $message = "Successfully Uploaded"  #this i will be having an entry in log file.
        }
    }