SharePoint: Upload File in Document Library Using PowerShell

SharePoint: Upload File in Document Library Using PowerShell

Use UploadFileInLibrary function to upload a file in SharePoint document Library.

Parameters : 
  1. $webUrl - Mandatory - SharePoint Web Url - e.g. http://server:port/ 
  2. $DocLibName - Mandatory - SharePoint Library Name 
  3. $FilePath - Mandatory - File Path on hard drive , e.g. .\abc.xlsx

function UploadFileInLibrary
{
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [string]$webUrl,
    [Parameter(Mandatory=$true)]
    [string]$
DocLibName,
    [Parameter(Mandatory=$true)]
    [string]$
FilePath
    )
    

  
    Start-SPAssignment -Global 
    $spWeb = Get-SPWeb -Identity $webUrl
    $spWeb.AllowUnsafeUpdates = $true;
    $List = $spWeb.Lists[$DocLibName]
    $folder = $List.RootFolder
    $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
    $File= Get-ChildItem $FilePath
    [Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile("/" + $folder.Url + "/" + $File.Name)
    $flagConfirm = 'y'
    if($spFile.Exists -eq $true)
    {
        $flagConfirm = Read-Host "File $FileName already exists in library $DocLibName, do you    want to upload a new version(y/n)?"
    }
   
    if ($flagConfirm -eq 'y' -or $flagConfirm -eq 'Y')
    {
        $fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
        #Add file
        write-host -NoNewLine -f yellow "Copying file " $File.Name " to " $folder.ServerRelativeUrl "..."
        [Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($folder.Url + "/" + $File.Name, [System.IO.Stream]$fileStream, $true)
        write-host -f Green "...Success!"
        #Close file stream
        $fileStream.Close()
        write-host -NoNewLine -f yellow "Update file properties " $spFile.Name "..."
        $spFile.Item["Title"] = "Document Metrics Report"
        $spFile.Item.Update()
        write-host -f Green "...Success!"
    }  
    $spWeb.AllowUnsafeUpdates = $false;



    Stop-SPAssignment -Global  
}


Function  Calling -

$webUrl = "http://sever:port"
$DocLibName = "DocLib1"
$filePath =  ".\text.xlsx"
UploadFileInLibrary $webUrl  $DocLibName $filePath
Leave a Comment
  • Please add 1 and 4 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Richard Mueller edited Revision 1. Comment: Removed extra space from tag "SharePoint  2010"

Page 1 of 1 (1 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • This article will benefit from See Also section

  • Richard Mueller edited Revision 1. Comment: Removed extra space from tag "SharePoint  2010"

Page 1 of 1 (2 items)