Uploading files to Sharepoint using powershell

Today I got a bit creative and threw together a small example for my students about how you can use powershell to upload files to Sharepoint. The script doesn’t have any error handling or anything of the sort, I leave that up to whomever uses the code as a bas.. . It takes a site url, and library name as parameters and then uploads the argument list. The file is also attached to this post.

  1. param($site=$(throw “You must specify a site”), $list=$(throw “You must specify a list”))
  2. if ($args.count -le 0) { throw “You must supply atlest one file to upload” }
  4. [void][System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SharePoint”)
  5. $spSite = New-Object Microsoft.SharePoint.SPSite($site)
  6. $spWeb = $spSite.OpenWeb()
  7. $spList = $spWeb.GetFolder($list)
  8. $spFiles = $spList.Files
  10. for ($i=0; $i -le $args.count;$i++)
  11. {
  12.  $fileInfo = Get-ChildItem $args[$i]
  13.  $fileContent = Get-Content $fileInfo -encoding byte
  14.  $fileName = “{0}/{1}” -f $list, $fileInfo.Name
  15.  $fileMetadata = New-Object HashTable
  16.  $spFile = $spFiles.Add($fileName, $fileContent, $fileMetadata, $true)
  17. }

Inspired by Sharepoint MVP Tobias Zimmergren and his example of doing it in C#