Search code examples
sharepointsharepoint-2019

Upload a file from local drive to Sharepoint Onpremise


I am looking for a way to program an auto upload of any files in a folder (ex : c:/folder/file.txt) to Sharepoint Library.

I have a Sharepoint 2019 OnPremise. Is there a way to do it with the API or PowerShell ?

I am not looking for a Power Automate solution, thank you.


Solution

  • You could use following PowerShell to upload files in the SharePoint 2019.

    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
      
    #Function to Upload File
    Function Upload-AllFilesFromDir($WebURL, $DocLibName, $FolderPath)
    {
        #Get the Web and List to upload the filen 
        $web = Get-SPWeb $WebURL
           
        #Get the Target Document Library to upload
        $List = $Web.GetFolder($DocLibName)
      
        #Get the Files from Local Folder
        $Files = Get-ChildItem $FolderPath #You can filter files by: -filter “*.pdf”
     
        #upload the files
        Foreach ($File in $Files)
        {
            #Get the Contents of the file to FileStream
            $stream = (Get-Item $file.FullName).OpenRead()
         
            # Set Metadata Hashtable For the file - OPTIONAL
            $Metadata = @{"Country" = "United States"; "Domain" = "Sales"}
         
            #upload the file             
            $uploaded = $List.Files.Add($File.Name, $stream, $Metadata, $TRUE)
         
            #dispose FileStream Object
            $stream.Dispose()
        }
    }
       
    #call the upload function
    Upload-AllFilesFromDir "https://SharePoint/sites/sales/" "Shared Documents" "C:\Documents\"