Friday 2 May 2014

Upload file to Document Library

Sometimes, you want to quickly upload a file to a document library, especially when you're using a sandboxed solution and you can't store your javascript or StyleSheet Files in the Layouts folder, long ago I mentioned that you could create a batch file that would xcopy your files into the layouts folder hastening the develop/debug cycle, well this is the same thing for Sandbox solutions.

function LoadSharePointPowerShellEnviroment
    write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Magenta
    Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
    Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green


# Set the variables
$WebURL =  "https://stiteCollection/sites/Marks"
$DocLibName = "SiteAssets"
$FilePath = "C:\Users\SPDevFAdmin\Documents\Scripts\AppLoader.js"

$web = Get-SPWeb $WebURL
$List = $web.GetFolder($DocLibName)
$Files = $List.Files

# Get just the name of the file from the whole path
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)

# Load the file into a variable
$File= Get-ChildItem $FilePath

Write-Host "uploading file $File " -ForegroundColor Yellow
$stream = $file.OpenRead()

# Upload it to SharePoint
$done = $Files.Add($DocLibName +"/" + $FileName, $stream,$true)

Write-Host "$done has been uploaded" -ForegroundColor Magenta

    Write-Host "dispose stream" -ForegroundColor Yellow

if($web -ne $null){
    Write-Host "dispose web" -ForegroundColor Yellow