3

I've tried converting these code snippets to PowerShell:

ClientContext context = new ClientContext("http://spdevinwin");
   2:  
   3: Web web = context.Web;
   4:  
   5: FileCreationInformation newFile = new FileCreationInformation();
   6: newFile.Content = System.IO.File.ReadAllBytes(@"C:\Work\Files\17580_FAST2010_S05_Administration.pptx");
   7: newFile.Url = "17580_FAST2010_S05_Administration 4MB file uploaded via client OM.pptx";
   8:  
   9: List docs = web.Lists.GetByTitle("Documents");
  10: Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
  11: context.Load(uploadFile);
  12: context.ExecuteQuery();
  13: Console.WriteLine("done");

and:

// FileInfo in System.IO namespace
var fileCreationInformation = new FileCreationInformation();

byte[] bytefile = System.IO.File.ReadAllBytes(“c:\\test\Test2.txt”);
fileCreationInformation.Content = bytefile;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = “http://astro/MyLibrary/MyFolder/Test2.txt”;

// CurrentList is a client OM List object
CurrentList.RootFolder.Files.Add(fileCreationInformation);
Context.ExecuteQuery();

But I get errors on the Update() and Add($file) methods

fred123
  • 31
  • 1
  • 3

2 Answers2

0

Rather than using the Client Object Model, the accepted way to upload files to SharePoint with PowerShell is to use the SharePoint PowerShell Cmdlts. You can use something similar to the following code:

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

$Library = "My Library"
$siteurl = "http://MyWebApp/sites/SiteName"
$FilePath = "C:\Test\test2.txt"

# Get Web site
$Web = Get-SPWeb $SiteUrl

# Get Library
$docLibrary = $web.Lists[$Library]
$folder = $docLibrary.RootFolder

# Get the file
$File = Get-ChildItem $FilePath

# Build the destination SharePoint path
$SPFilePath = ($folder.URL + "/" + $File.Name)

$spFile = $folder.Files.Add($SPFilePath, $File.OpenRead(), $true)  #Upload with overwrite = $true (SP file path, File stream, Overwrite?)

For a reusable function that you can use to upload files, overwrite, approve, and check in, use the cmdlet that I created here: http://pastebin.com/Tvb4LfZV

HAL9256
  • 12,384
  • 1
  • 34
  • 46
0

You'll only be able to use the SharePoint PowerShell cmdlets if you are running on the server. They don't work remotely, especially for SharePoint Online.

You didn't include all of your PowerShell code but I'll guess you weren't calling ClientContext.Load and ClientContext.ExecuteQuery after each step of getting the list and loading the file to the server.

Reference for using many PowerShell CSOM scenarios

Craig Riter
  • 106
  • 4