Search code examples
powershellsharepointsharepoint-2010

Upload and Check-in File to SharePoint from a Remote Machine


I am trying to upload and check-in files to a SharePoint Intranet site using Powershell. This script will be run on a remote machine, NOT the server hosting the site. Uploading the files was relatively easy following the instructions given here.

Below is a small section of the process I am using to upload the files. They are successfully uploaded but remained checked out to me. Is there anyway to check these files in using Powershell?

$destination = "http://mycompanysite.com/uploadhere/Docs” 
$File = get-childitem “C:\Docs\stuff\To Upload.txt”

# Upload the file 
$webclient = New-Object System.Net.WebClient 
$webclient.UseDefaultCredentials = $true
$webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName)

Unfortunately using the SharePoint PowerShell module won't work since this is run on a remote machine.

Thanks!


Solution

  • You might have an easier time using Microsoft.SharePoint.Client instead which you can download from here: Download SharePoint Server 2013 Client Components

    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" #loads sharepoint client runtime
    $destination = "http://mycompanysite.com/uploadhere"
    $listName = "Docs"
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($destination)
    $context.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials #signs you in as the currently logged in user on the local host
    $context.RequestTimeout = 10000000
    $list = $context.Web.Lists.GetByTitle($listName)
    $context.Load($list)
    $context.ExecuteQuery()
    
    $stream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
    $fileOptions = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $fileOptions.Overwrite = $true
    $fileOptions.ContentStream = $stream
    $fileOptions.URL = $File
    $upload = $list.RootFolder.Files.Add($fileOptions)
    $context.Load($upload)
    $context.ExecuteQuery()
    
    $upload.CheckIn("My check in message", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn) #other options can be looked at here: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.checkintype.aspx
    $context.ExecuteQuery() #finally save your checkin