Monday, May 13, 2013

PowerShell: Uploading documents from file system during deployment

The following is the script to upload document from file system.
try
{
    #Run with app pool account privileges
    [Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges({
     Write-Host "Uploading document...." -ForegroundColor Cyan

    #Upload required documents to document libraries
    $Web = Get-SPWeb $SiteCollectionURL
    $List = $Web.GetFolder($DocumentLibraryName)

    if ($List -ne $null)
    {
        $FullLocalFileName = $DocumentsLocalPath + $DocumentLibraryFile1 

        #Read the file
        $File = Get-ChildItem $FullLocalFileName 

        #Add file to the collection
        [Microsoft.SharePoint.SPFile]$SPFile = $Web.Files.Add($DocumentLibraryName + "/" + $DocumentLibraryFile1, $File.OpenRead(),$true)

        #Update fields
        $SPFile.Item["FildName"] = $Metadatavalue;
        $SPFile.Item.Update()

        $Web.Update()

        Write-Host "Uploaded document..."$FullLocalFileName -ForegroundColor Yellow
    }
 })
}
catch 
{
    Write-Host "Site collection url:"$SiteCollectionURL -ForegroundColor Yellow
    Write-Host "Document being uploaded is:"$FullLocalFileName -ForegroundColor Yellow
    Write-Host "Error."$Error[0].ToString() -ForegroundColor Red
}

No comments:

Post a Comment