Upload files with metadata

14/10/2012 22:25

#Upload pictures with informations
 
#input parameters
$srcPath="C:\cham.Install\NewsPages" #source folder for Pages on file system
$siteUrl="https://localhost/sites/news" #$SiteUrl #got from Run.ps1
$libraryUrl=$siteUrl+"/Pages"
 
#metadata (NewsTitle, PageContent, Highlighted) for each page
[array] $metadata=@(("Prvy New", "<h2>Pozor1</h2>", $true),
                        ("druhy New", "<h2>Pozor2</h2>", $false),
                        ("treti New", "<h2>Pozor3</h2>", $true))
 
#upload all files in $srcPath folder
#TODO check format/file extension
$pictures=get-childitem $srcPath
 
#cls
 
 
 # check to ensure Microsoft.SharePoint.PowerShell is loaded
    $snapin=Get-PSSnapin | Where-Object {
       $_.Name -eq 'Microsoft.SharePoint.Powershell'}
       if ($snapin -eq $null) {
       Write-Host "Loading SharePoint Powershell Snapin"
       Add-PSSnapin "Microsoft.SharePoint.Powershell"
       }
 
 
 
function UploadFile
{
    param([string]$srcPath,
            [string]$fileName,
            [string]$libraryUrl,
            [array]$metadata)
  
  try
  {  
 $web=get-spweb $siteUrl
 
 $libraryFolder=$libraryUrl.substring($libraryUrl.lastIndexOf('/')+1, $libraryurl.length-$libraryUrl.lastIndexOf('/')-1)
 $folder=$web.GetFolder($libraryFolder)        
 $file=get-childitem ($srcPath + "\" + $fileName)
 $files=$folder.Files
 
      write-host $metadata[0]
      write-host $metadata[1]
      write-host $metadata[2]
     
      $newsTitle=$metadata[0]
      $pageContent=$metadata[1]
      $highlighted=$metadata[2]
 
 $itemMetadata = @{}
 #$itemMetadata.add("Title", $newsTitle)
 #$itemMetadata.add("Page Content", $pageContent)
 #$itemMetadata.add("chamNewsHighlighted", $highlighted);
 
 $newFile=$files.Add($libraryUrl+"/" + $fileName, $file.OpenRead(), $itemMetadata,  $true) #true for overwrite
      $newFile.Item["Page Content"]=$pageContent
      $newFile.Item["Title"]=$newsTitle
      $newFile.Item["chamNewsHighlighted"]=$highlighted
      $newFile.Item.Update()
   
 #check in only when files are checked out, when it's publishing site
 $spfile = $files[$fileName]
 write-host "file checkout status:" $spfile.checkOutStatus;
 if($spfile.checkOutStatus -ne "None" -and $spfile.checkOutStatus -ne $null)
 {
$spfile.checkIn("Checked in by Powershell", [Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
start-sleep -s 5
$spfile.Approve("Approved by Powershell")
 }
  }
  catch [Exception]
  {
      write-error $_
  }
  finally
  {
  if($web -eq $null)
    {
    $web.dispose()
    }
   
  }          
}
 
 
 
 
$i=0
foreach($picture in $pictures)
{
    UploadFile -srcPath $srcPath -fileName $picture.Name -libraryUrl $libraryUrl -metadata $metadata[$i]
    $i++
}