Wednesday, 6 May 2015

Upload file into SharePoint doument library with metadata using PowerShell

In this post we will see how to upload the file into the document library and insert/update the metadata columns. I am having 1 people picker data types/user group columns and 1 single line of text columns.

Below is the PowerShell to upload documents in PowerShell and update the metadata:

        if((Get-PSSnapin | Where {$_.Name -
        eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
            Add-PSSnapin Microsoft.SharePoint.PowerShell;

           #Site Collection where you want to upload files
          $siteCollUrl = "YourSiteURL"
          #Document Library where you want to upload files
         $libraryName = "DocLibName"
         #Physical/Network location of files
          $reportFilesLocation  = "D:\FileUpload"

        $spSourceWeb = Get-SPWeb $siteCollUrl;
        $spSourceList = $spSourceWeb.Lists[$libraryName];

            if($spSourceList -eq $null)
           Write-Host "The Library $libraryName could not be found."

   $files = ([System.IO.DirectoryInfo] (Get-Item 
  foreach($file in $files)
    #Open file
   $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

   #Add file
   $folder =  $spSourceWeb.getfolder($libraryName)

   Write-Host "Copying file $file to $libraryName..."
   $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name,   
   [System.IO.Stream]$fileStream, $true)

$item = $spFile.Item;
$item["TextOrChoiceColumnInternalName"] = "New Value"
$spUser = Get-SPUser -Identity "domain\username" -Web $spSourceWeb;
$item["UserFieldInternalName"] = $spUser;
#Use SystemUpdate($false) if you don't want to increase the version of the item..

   #Close file stream
Write-Host "Files have been uploaded to $libraryName."

Using this PowerShell script you can upload documents with metadata.

To check in a file use:
$spFile.CheckIn("Checked In By Administrator")

To publish a file:
$spFile.Publish("Automatically published by Powershell")

To approve a file:
$spFile.Approve("Automatically approved by by Powershell");

Hope this helps!!!

1 comment:

  1. Thanks for the blog.

    I was able to do this using JS.

    Check here:


Related Posts Plugin for WordPress, Blogger...