PoshCode Logo PowerShell Code Repository

Publish-File by halr9000 17 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2122"></script>download | new post

Use this to upload one or more files to a SharePoint document library. Should also work with any WebDAV service, although that hasn’t been tested. The filename parameter expects fileinfo objects. Easiest way to do so is to pass them on the pipeline from Get-ChildItem. This script is a refinement of a technique that I first saw here: http://blogs.flexnetconsult.co.uk/colinbyrne/PermaLink,guid,a326572f-8f78-4c80-86d5-1fe52cbd6fe5.aspx.

The credential parameter is optional. If you do not supply it, then your currently logged-in credentials are used.

  1. # Note that this version will not descend directories.
  2. function Publish-File {
  3.         param (
  4.                 [parameter( Mandatory = $true, HelpMessage="URL pointing to a SharePoint document library (omit the '/forms/default.aspx' portion)." )]
  5.                 [System.Uri]$Url,
  6.                 [parameter( Mandatory = $true, ValueFromPipeline = $true, HelpMessage="One or more files to publish. Use 'dir' to produce correct object type." )]
  7.                 [System.IO.FileInfo[]]$FileName,
  8.                 [system.Management.Automation.PSCredential]$Credential
  9.         )
  10.         $wc = new-object System.Net.WebClient
  11.         if ( $Credential ) { $wc.Credentials = $Credential }
  12.         else { $wc.UseDefaultCredentials = $true }
  13.         $FileName | ForEach-Object {
  14.                 $DestUrl = "{0}{1}{2}" -f $Url.ToString().TrimEnd("/"), "/", $_.Name
  15.                 Write-Verbose "$( get-date -f s ): Uploading file: $_"
  16.                 $wc.UploadFile( $DestUrl , "PUT", $_.FullName )
  17.                 Write-Verbose "$( get-date -f s ): Upload completed"
  18.         }
  19.        
  20. }
  21.  
  22. # Example:
  23. # dir c:\path\files* | Publish-File -Url "https://mysharepointsite.com/personal/userID/Personal%20Documents"

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me