SharePoint 2010: Upload File in Document Library Using PowerShell
Introduction
This article contains a PowerShell function that can be used to upload a file to a document library.
The Function
**Parameters : **
- $webUrl - Mandatory - SharePoint Web Url - e.g. http://server:port/
- $DocLibName - Mandatory - SharePoint Library Name
- $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
}
Calling the Function
$webUrl = "http://sever:port"
$DocLibName = "DocLib1"
$filePath = ".\text.xlsx"
UploadFileInLibrary $webUrl $DocLibName $filePath
Other Languages
This article is also available in the following languages: