Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Upload directory recursively to Sharepoint

For the times when you have to be icky and use it, here you go. Also this method uses the application server itself and the admin credential, because I was unable to authenticate using claims auth only from Powershell for using the client-side functions.

#    Upload-Directory-To-Sharepoint is adapted from https://stackoverflow.com/questions/20237294/upload-file-to-sharepoint-document-library-using-powershell
#    with some examples from https://www.sharepointdiary.com/2016/08/sharepoint-online-create-folder-using-powershell.html

Function Upload-Directory-To-Sharepoint {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory = $False)][string]$ParentDirectory = ".",
        [Parameter(Mandatory = $False)][string]$SPSite = "https://sp.example.com/admin/test",
        [Parameter(Mandatory = $False)][string]$Library = "Documents"
    )
    $web = Get-SPWeb -Identity $SPSite

    If ($web) {
        try {
            $list = $web.Lists.TryGetList($Library)
            # Change to the requested dir, so the relative paths all start with "." which can be easily cleaned up.
            Set-Location $ParentDirectory
            $files = Get-ChildItem -Path "." -Force -Recurse
            ForEach ($dir in $files | ? { $_.PSIsContainer } ) {
                # and we depend on them being ordered from parent directory down to child directories.
                $RelativeName = (($dir | Resolve-Path -Relative ) -Replace "^\.\\" ) -Replace "\\","/"
                $newDir = "$($list.RootFolder.ServerRelativePath)/$($RelativeName)"
                If ($PsCmdlet.ShouldProcess("Mkdir $($SPSite)$($newDir)")) { $results = $web.Folders.Add($newDir) ; }
            }
            ForEach ($file in $files | ? { !($_.PSIsContainer) -And $_.Name -ne "Thumbs.db" } ) {
                $RelativeName = (($file | Resolve-Path -Relative ) -Replace "^\.\\" ) -Replace "\\","/"
                $newFile = "$($list.RootFolder.Path)/$($RelativeName)"
                $newFileUrl = "$($SPSite)/$($newFile)"
                $stream = $file.OpenRead()
                If ($PSCmdlet.ShouldProcess("Upload $($newFileUrl)")) {
                    $done = $list.RootFolder.Files.Add("$($newFile)", $stream, $true)
                    Write-Host """$($SPSite)$($done.ServerRelativePath)"" Uploaded into the Site"    
                }
            }
        }
        catch {
            $ErrorMessage = $_.Exception.Message
            Write-Error $ErrorMessage
        }
    }

    else { Write-Host "Site Doesn't exist" }
    $list.Update();
}

Comments