A while back I posted an article on downloading files from SharePoint using PowerShell (see here) that generated a few questions about uploading files. So… here's a few uploading scripts. Don't stop here though, there are many other examples on the web. Google/Bing is your friend!
An Upload with Metadata Script
This script not only uploads files, but lets you add metadata.
# Set a few variables $file = "C:\test\myTestFile.txt" $TTNwebUrl = "http://server/sites/yoursite" $library = "Team Documents" $overWriteExisting = $True #or add new version if versioning enabled # do a little SharePoint setup $web = Get-SPWeb $TTNwebUrl $files = $web.GetFolder($library).Files $fileNameForLibrary = $file.Substring($file.LastIndexOf("\")+1) # read the file $data = Get-ChildItem $file # add any needed metadata $metadata = @{ "Project ID" = "A-200"; "Region" = "North" } # or if no metadata needed: $metadata = @{} # do the upload (the following is one line) $newfile = $files.Add($library + "/" + $fileNameForLibrary, $data.OpenRead(), $metadata, $overWriteExisting)
And if you are a "one liner" PowerShell scripter:
(Get-SPWeb "http://server/sites/yoursite").GetFolder("Team Documents").Files.Add("Team Documents/myTestFile.txt", (Get-ChildItem "C:\test\myTestFile.txt").OpenRead(), $True)
And with metadata:
(Get-SPWeb "http://server/sites/yoursite").GetFolder("Team Documents").Files.Add("Team Documents/myTestFile.txt", (Get-ChildItem "C:\test\myTestFile.txt").OpenRead(), @{ "Project ID" = "A-200"; "Region" = "North" }, $True)
Upload an Attachment with a New List Item
I generally recommend linking from a list item to a file in a library, but if you want to add attachments to a list item, here's a sample script:
# Set a few variables $TTNweb = Get-SPWeb "http://yourServer/sites/yourSite"; $list = $TTNweb.lists["yourListName"]; $filePath = "C:\SampleDocs\yourSampleFile.JPG"; # Create a new list item: $item = $list.items.Add(); $item["Title"] = "Test Title"; # set any addition metadata $item.Update(); # Upload the file: $bytes = [System.IO.File]::ReadAllBytes($filePath); $item.Attachments.Add([System.IO.Path]::GetFileName($filePath), $bytes); $item.Update();
Looking for a PowerShell course for SharePoint administrators and auditors?
SharePoint 2010 and 2013 Auditing and Site Content Administration using PowerShell
https://www.microsoft.com/en-us/learning/course.aspx?cid=55095A
Or you can attend my class in Cincinnati (locally or remotely)!
http://www.maxtrain.com/Classes/ClassInfo.aspx?Id=119394
.
1 comment:
GREAT ARTICLE !
Thanks a lot, I love the one-liner :-)
Chantal B.
Post a Comment
Note to spammers...
Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.