Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Im trying to upload a file to a document library in SharePoint 2010 via powershell. Ive followed about 5 different blog posts, most recently the one found here - http://www.sharepoint-howto.com/2012/03/14/sharepoint-2010-how-to-add-files-in-a-folder-to-a-sharepoint-library-with-powershell/

This is my powershell script, but the file just wont upload.

$siteurl = "http://intranet.org/IT" 
$spWeb = Get-SPWeb $siteurl 
$docLibraryName = "Shared Documents" 
$localFolderPath = "C:\ServerStatus\Output" 
$docLibrary = $spWeb.Lists[$docLibraryName]  

$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles() | ForEach-Object { 
$fileStream = ([System.IO.FileInfo] (Get-Item $_.FullName)).OpenRead() 
$contents = new-object byte[] $fileStream.Length 
$fileStream.Read($contents, 0, [int]$fileStream.Length); 
$fileStream.Close(); 
write-host "Copying" $_.Name "to" $docLibrary.Title "in" $spWeb.Title "..." 
$folder = $docLibrary.RootFolder 
$spFile = $folder.Files.Add($folder.Url + "/" + $_.Name, $contents, $true) 
$spItem = $spFile.Item  
} 

When I run the commands individually, the variables $spFile and $spItem are empty, any idea's why these commands would fail?

share|improve this question
add comment

3 Answers 3

As far as I can see it ought to work, but you may want to try a more PowerShell like variant:

$siteurl = "http://intranet.org/IT"  
$spWeb = Get-SPWeb $siteurl  
$docLibraryName = "Shared Documents"  
$localFolderPath = "C:\ServerStatus\Output"  
$docLibrary = $spWeb.Lists[$docLibraryName]  

$folder = $docLibrary.RootFolder  
Get-ChildItem $localFolderPath | Where-Object {!$_.PSIsContainer} | ForEach-Object {  
    $contents = [Byte[]](Get-Content $_.FullName -Encoding Byte)
    write-host "Copying" $_.Name "to" $docLibrary.Title "in" $spWeb.Title "..."  
    $spFile = $folder.Files.Add($folder.Url + "/" + $_.Name, $contents, $true)  
    $spItem = $spFile.Item   
}
share|improve this answer
    
Hey! Thanks for the answer, but I just published what the resolution was. Appreciate the modified code though! –  ewitkows Oct 19 '12 at 20:46
add comment
up vote 0 down vote accepted

OK, found that the file wouldn't publish because the process that created my excel file still had a lock on it. I had to manipulate the script to release the Excel COM object, and then the script above was able to publish the results.

share|improve this answer
add comment

If it is of any help, I wrote up some PowerShell scripts recently out of which one is to upload documents:

http://vrdmn.blogspot.in/2012/10/everyday-powershell-scripts-for.html

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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