Skip to content

Instantly share code, notes, and snippets.

@vgrem
Created September 14, 2017 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgrem/9a25f1687428c16cad4f0de0dcc5c23b to your computer and use it in GitHub Desktop.
Save vgrem/9a25f1687428c16cad4f0de0dcc5c23b to your computer and use it in GitHub Desktop.
Demonstrateds how to upload a file into SharePoint Online via WebDAV
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
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\SharePoint Client Components\16.0\Assemblies\Microsoft.Online.SharePoint.Client.Tenant.dll"
function Connect-SPO ([string] $Username, [string]$Password, [string]$Url) {
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $(ConvertTo-SecureString -AsPlainText $Password -Force))
$Context.ExecuteQuery()
$AuthenticationCookie = $Context.Credentials.GetAuthenticationCookie($Url, $true)
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$WebSession.Credentials = $Context.Credentials
$WebSession.Cookies.SetCookies($Url, $AuthenticationCookie)
$FormsDigest = $Context.GetFormDigestDirect()
$WebSession.Headers['X-RequestDigest'] = $FormsDigest.DigestValue
$Context.Dispose()
return $WebSession
}
#Usage
$WebUrl = "https://contoso.sharepoint.com/"
$Username = "john@contoso.onmicrosoft.com"
$Password = ""
$filePath = "C:\Users\user\Documents\Sample.png"
$FolderUrl = "/Documents"
$FileInfo = New-Object System.IO.FileInfo($filePath)
#Connect
$Session = Connect-SPO -Username $Username -Password $Password -Url $WebUrl
# Upload file
$targetFileUrl = "$WebUrl/documents/$($FileInfo.Name)"
Invoke-WebRequest -Uri $targetFileUrl -Method Put -WebSession $Session -InFile $filePath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment