6

I'd like to upload files from my c drive on my computer to my SharePoint intranet site with url http://kmsbs.

I would like the files to go to the documents library on that site.

Does anyone know how to accomplish this task with a PowerShell script or have a PowerShell script that I can use? The reason I want to use PowerShell is so that I can have task manager schedule the script to run once a day.

Also, I'm not using the computer that the SharePoint site and server are hosted on. Is it still possible to do this or do i have to be using the hosting computer?

4 Answers 4

7

You can use following PS script provided by Todd Klindt in this blog post:

$WebURL = "http://portal.contoso.com/sites/stuff" 
$DocLibName = "Docs" 
$FilePath = "C:\Docs\stuff\Secret Sauce.docx"
$Web = Get-SPWeb $WebURL 
$List = $Web.GetFolder($DocLibName) 
$Files = $List.Files
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
$File= Get-ChildItem $FilePath
$Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(),$false) 
$web.Dispose()
5
  • Thank you very much for your help, what is $DocLibName there?
    – ajs
    Commented Oct 8, 2015 at 18:07
  • 1
    In the script document library name is defined as "Docs". You can change it in your own version. To make a PS script to sleep I'd suggest using Start-Sleep command. For instance, "Start-Sleep -s 10" will pause for 10 seconds.. More info about the command you can get using "Get-Help Start-Sleep -Full" command. Hope Iit'd be useful for you.
    – andrewsha
    Commented Oct 8, 2015 at 19:11
  • for some reason when i run this code i get the error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." how do i correct this? Thanks again
    – ajs
    Commented Oct 29, 2015 at 18:48
  • Hi, what does the $false do after the Openread() command in the script, when adding a item to the list?
    – emo
    Commented Dec 26, 2016 at 20:42
  • The third parameter of the method Add specifies if the file within the library that has the same name as the file that is adding should be replace ($true) or not ($false).
    – ameliapond
    Commented Jun 2, 2017 at 14:33
1

Migrating files from our local file system to one of the Document Library in SharePoint Site can be achieved easily using CSOM PowerShell.

First get the client namespaces installed on your machine

Get SharePoint 2013 Client Components and install on your machine from where you wish to execute the script.

Once you finish installing the client components, all the client namespaces will be located at below location.

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\

Add references of client namespaces in your PowerShell script

Add-Type -Path 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'

Connect to SharePoint Site.

# SharePoint URL 
#
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext("http://YourSite")
$web = $ctx.Web

# Authenticating
#
$cred = Get-Credential
$ctx.Credentials = $cred

# Get Document Library
#
$DocLib = $web.Lists.GetByTitle("NameOfYourDocLib")

# Load the object
#
$ctx.Load($web)
$ctx.Load($DocLib)
$ctx.ExecuteQuery()

Get your files from the file system into an object.

# Get all files
#
$Files = Get-ChildItem -Path "c:\TestFolder" | ? {$_.psIsContainer -eq $False}

Read each file and upload it onto a Document Library.

# Upload all files in the root folder of the document library
#
Foreach ($File in $Files) {

    Write-Host "Uploading file.." -ForegroundColor Green

    $FileFullName = $File.FullName
    $FileStream = New-Object IO.FileStream($FileFullName, [System.IO.FileMode]::Open)
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.ContentStream = $FileStream
    $FileCreationInfo.URL = $File.Name
    $FileUpload = $DocLib.RootFolder.Files.Add($FileCreationInfo)
    $ctx.Load($FileUpload)
    $ctx.ExecuteQuery()
}
12
  • in the credential piece of this code do i set the variable equal to username-password??
    – ajs
    Commented Oct 22, 2015 at 17:12
  • Get-Credential is PowerShell's function, it will give you a pop-up where you can enter your user name and password .
    – Asad Refai
    Commented Oct 23, 2015 at 6:39
  • when i run the function i get an error on the first line saying cannot find type make sure the assembly containing this type is loaded, do you know how i fix that by any chance? thanks
    – ajs
    Commented Oct 27, 2015 at 17:18
  • I'm running the script from a computer that doesn't have the sharepoint server on it, but can access the intranet site; is that the problem? Do i have to run it from the hosting computer?
    – ajs
    Commented Oct 27, 2015 at 17:56
  • You can certainly run the script from a computer which does not have SharePoint. Provided you have installed client components. Find it here microsoft.com/en-us/download/details.aspx?id=35585
    – Asad Refai
    Commented Oct 27, 2015 at 19:38
0
Add-PSSnapin microsoft.sharepoint.powershell
$web = Get-SPWeb "http://dc01:9876"
$lst = $web.Lists.TryGetList("Style Library")
$DirLoc = "C:\Work\Style Library\20April2015"

$relativeUrl = $lst.RootFolder.ServerRelativeUrl;

function UploadToLibrary($spurl,$filepath){
    Get-ChildItem -path $filepath -Directory |ForEach-Object {
        $FldrName=($spurl,$_.Name -join "/")
        $CheckFolder= $web.GetFolder($FldrName)
        if(-not $CheckFolder.Exists)
        {
            $tmp=$web.GetFolder($spurl).SubFolders.Add($FldrName);
        }
        UploadToLibrary ($spurl,$_.Name -join "/") ($filepath,$_.Name -join "\") 
    }
    $FilesToAdd=$web.GetFolder($spurl)
    Get-ChildItem -path $filepath -File |ForEach-Object {
        $_.FullName
        $bytes = [System.IO.File]::ReadAllBytes($_.FullName)
        $x=$FilesToAdd.Files.Add($_.Name,$bytes,$true);
    }
}

UploadToLibrary $relativeUrl $DirLoc
0

Nice post for Upload files from file share location to sharepoint library or folder inside a library.

http://naga1208.blogspot.in/2015/10/upload-files-to-sharepoint-site-using.html

Steps to upload files from file share location to sharepoint library with relevant metadata

$webUrl  = "http://contoso.com";  #http://contoso.com Replace with your Site Url

$docLibraryName = "Documents"; ##Documents - Replace with your library name

$docFolderName =  "SharePoint"; ##SharePoint - Replace with Folder name if you have sub folders in Library

$docNumber = "SeachDocument.docx"; ##SeachDocument.docx - Replace with File name which you will have in file share location

try
  {

   $inputRowCollection = Get-ChildItem $DocumentsRepositoryPath -Recurse | Where-Object {$_.Name -like $docNumber+ "*"}

   if($inputRowCollection.Count -eq 0)
   {
    $row.IsMigrated = "File Missing"
   }

   if($inputRowCollection.Count -eq 1)
   {
    $row.IsMigrated = UploadFileInLibrary $webUrl  $docLibraryName $inputRowCollection.PSPath $docFolderName
   }
   elseif($inputRowCollection.Count -ge 1)
   {
    $row.IsMigrated = "Duplicate Documents"
   }
  }          
  catch          
  {
   Write-Host "File Path : ($inputRowCollection.PSPath) - Error ($documentData): "$_.Exception -f Red;
   Write-Output "File Path : ($inputRowCollection.PSPath) - Error ($documentData): "$_.Exception >> $ExceptionLogFile
   $logData = $logData + "`tNA`t" + $_.Exception + "`tFail`tNA"  
  }

#Function to upload Document into SharePoint library
function UploadFileInLibrary          
{
 [CmdletBinding()]          
 Param(          
 [Parameter(Mandatory=$true,ValueFromPipeline=$true)]          
 [string]$webUrl,          
 [Parameter(Mandatory=$true)]          
 [string]$DocLibName,          
 [Parameter(Mandatory=$true)]          
 [string]$FilePath,            
 [Parameter(Mandatory=$false)]          
 [string]$FolderName
 )              

  try
  {

 #region Code for Migration

 $spWeb = Get-SPWeb -Identity $webUrl

 $List = $spWeb.Lists[$DocLibName]          
 $folder = $List.RootFolder          
 if($FolderName -ne "")
 {
  $folder = $list.RootFolder.SubFolders[$FolderName]
 }
 $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)          
 $File= Get-ChildItem $FilePath  
 $fileExtension = ([System.IO.FileInfo] (Get-Item $File.FullName)).Extension
 [Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile($folder.Url + "/" + $docNumber+$fileExtension)          
 $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)?"          
  return "Document Exist."
 }          

 if ($flagConfirm -eq 'y' -or $flagConfirm -eq 'Y')          
 {
  $spWeb.AllowUnsafeUpdates = $true;

  $fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
  $fileExtension = ([System.IO.FileInfo] (Get-Item $File.FullName)).Extension
    #Add file          
    write-host -NoNewLine -f yellow "Copying file " $File.Name " to " $folder.ServerRelativeUrl "..."          
    [Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($folder.Url + "/" + $docNumber+$fileExtension, [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 "..."

  #Check the whether exists or not in site
  $docContentType = $docContentType   

  if($docContentType -eq $IMS)
  {
   $docContentType = $List.ContentTypes[$docContentType]
   $spFile.Item["ContentTypeId"] = $docContentType.Id;
   $spFile.Item["Content Type"] = $docContentType.Name;
   $spFile.Item["Name"] = $docNumber
   $spFile.Item["Title"] = $docTitle     
   $spFile.Item.Update()          
   write-host -f Green "...Success!"
   $spFile.CheckIn("Checked In By Administrator");
            Write-Host "$($spFile.Name) Checked In" -ForeGroundColor Green
  } 

  $spWeb.AllowUnsafeUpdates = $false;
 }


 return "Uploaded";

 #endregion

 }
 catch
 {
  Write-Host "File Path : ($inputRowCollection.PSPath) - Error in DocumentsMigration method : "$_.Exception -f Red;
  Write-Output "File Path : ($inputRowCollection.PSPath) - Error in DocumentsMigration method: "$_.Exception >> $ExceptionLogFile
  return "Error while uploading";
 }
}
5
  • in that post you set variables in the first 4 lines; do i just change the variable names and it'll work from there? and what do i use instead of doc folder name there? the sharepoint documents library url?
    – ajs
    Commented Oct 22, 2015 at 16:45
  • $webUrl = "contoso.com"; contoso.com Replace with your Site Url $docLibraryName = "Documents"; Documents - Replace with your library name $docFolderName = "SharePoint"; SharePoint - Replace with Folder name if you have sub folders in Library $docNumber = "SeachDocument.docx"; - SeachDocument.docx - Replace with File name which you will have in file share location Commented Oct 29, 2015 at 7:51
  • Please do not post link-only answers. When the link breaks they are of no use Commented Oct 29, 2015 at 11:58
  • is the library the documents library on the sharepoint site or is it the library on your hard drive? and is doc number the file path to the file you want to upload??
    – ajs
    Commented Oct 29, 2015 at 17:58
  • Do we have library in hard drive? Library mean SharePoint Library --------- doc number mean it's keyword of file which will search and find the file in file share location. Commented Oct 30, 2015 at 5:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.