Upload File To SharPoint Folder

ADezii 1 Reputation point
2022-07-18T23:05:54.817+00:00

How can I programmatically Upload a File to a SharePoint Folder using a PowerShell Script?

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 39,916 Reputation points
    2022-07-19T15:24:19.347+00:00

    Hi there,

    Here is how to upload files to SharePoint Online:

    Load SharePoint CSOM Assemblies

    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

    Variables for Processing

    $WebUrl = "https://crescent.sharepoint.com/Sites/Sales"
    $LibraryName ="Documents"
    $SourceFile="C:\SitesToCreate.csv"
    $AdminName ="Salaudeen@Crescent .com"
    $AdminPassword ="password goes here"

    Setup Credentials to connect

    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminName,(ConvertTo-SecureString $AdminPassword -AsPlainText -Force))

    Set up the context

    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
    $Context.Credentials = $Credentials

    Get the Library

    $Library = $Context.Web.Lists.GetByTitle($LibraryName)

    Get the file from disk

    $FileStream = ([System.IO.FileInfo] (Get-Item $SourceFile)).OpenRead()

    Get File Name from source file path

    $SourceFileName = Split-path $SourceFile -leaf

    sharepoint online upload file powershell

    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.ContentStream = $FileStream
    $FileCreationInfo.URL = $SourceFileName
    $FileUploaded = $Library.RootFolder.Files.Add($FileCreationInfo)

    powershell upload single file to sharepoint online

    $Context.Load($FileUploaded)
    $Context.ExecuteQuery()

    Close file stream

    $FileStream.Close()

    write-host "File has been uploaded!"

    I hope this information helps. If you have any questions please let me know and I will be glad to help you out.


    --If the reply is helpful, please Upvote and Accept it as an answer--

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.