Tuesday 13 November 2012

Populate List with Attachment

once in a while you'll need to create a list that contains an attachment; why not use a document library or a documents set, well i'll tell you why. When I came up with this i was a nOOb and had no idea what I was doing. So this example is by no means a best practice, but hey maybe one day I'll come across a scenario where it'll come in handy, so hey toss it into the old toolbox for later.



$RootURL = "http://ssrdevinter.corp.windsor/"

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

function AddAttachment($item, $filePath)
{
    $bytes = [System.IO.File]::ReadAllBytes($filePath)
    $item.Attachments.Add([System.IO.Path]::GetFileName($filePath), $bytes)
    $item.Update()
}
     
function CreateJobPosting($newJobPost, $Title, $PostingID, $StartDate, $EndTime, $DepartmentIndex, $DescriptionPath)  
{
    $newJobPost["Title"] = $Title
    $newJobPost["PostingID"] = $PostingID
    $newJobPost["StartDate"] =  $StartDate
    $newJobPost["EndDate"] = $EndTime
    $newJobPost["Department"] = 1
    AddAttachment $newJobPost $DescriptionPath
    $newJobPost.update()
   
    Write-Host -ForegroundColor Green Job Posting: $Title Completed
}
 
try
{
    LoadSharePointPowerShellEnviroment
    $RootSite = new-object Microsoft.SharePoint.SPSite($RootURL)
    $jobWeb = $RootSite.rootweb.webs["cityhall"].webs["work-for-windsor"]
    $JobPostingList = $jobWeb.lists["JobPostingsListInstance"]
 
    CreateJobPosting $JobPostingList.items.Add() "It Weather Widget Updater" "IT100" ([DateTime]::Now) ([DateTime]::Now.addDays(15)) 1 "c:\test.txt"
    CreateJobPosting $JobPostingList.items.Add() "Barista" "IT001" ([DateTime]::Now) ([DateTime]::Now.addDays(5)) 1 "c:\test.txt"
    CreateJobPosting $JobPostingList.items.Add() "Bard" "IT002" ([DateTime]::Now) ([DateTime]::Now.addDays(5)) 1 "c:\test.txt"
    CreateJobPosting $JobPostingList.items.Add() "Easter Bunny" "IT003" ([DateTime]::Now) ([DateTime]::Now.addDays(5)) 1 "c:\test.txt"

}
catch [Exception]
{
    Write-Host -ForegroundColor Red "Error in  Create job Postings$_"
}
finally
{
    $jobWeb.Dispose()
}