Use PowerShell Cmdlets to Manage SharePoint Document Libraries

Use PowerShell Cmdlets to Manage SharePoint Document Libraries

  • Comments 30
  • Likes


Summary: Management of SharePoint 2010 document libraries by using Windows PowerShell cmdlets is explored in this Hey, Scripting Guy! Blog post.


Hey, Scripting Guy! Question Hey, Scripting Guy! Please tell me about document management with SharePoint and Windows PowerShell.

-- MK


Hey, Scripting Guy! Answer Hello MK,

Microsoft Scripting Guy Ed Wilson here. It is Thursday in Charlotte, North Carolina, and our last day with guest blogger Niklas Goude, who has been sharing his expertise with SharePoint and Windows PowerShell all week.

Niklas Goude is a Windows PowerShell MVP working at Enfo Zipper in Stockholm, Sweden. Niklas has extensive experience in automating and implementing SharePoint environments using Windows PowerShell. He has written a Windows PowerShell book for Swedish IT pros,, and is currently co-authoring a book with Mattias Karlsson titled, PowerShell for Microsoft SharePoint 2010 Administrators, which will be published in English by McGraw-Hill in October 2010. Parts of this post are taken from Chapter 16 of that book.

Niklas also runs the blog,, where he shares scripts, examples, and solutions for administrative tasks in Windows environments through Windows PowerShell.


Creating Document Libraries

Working with document libraries is similar to working with SharePoint lists, as described in yesterday’s post. In this post we will create a new document library and see examples of how to upload documents to a document library.

Creating a new document library using Windows PowerShell is very similar to the creation of any other type of list. We can use the same Add() method provided by the SPListCollection class. In the example below, we use the Get-SPWeb cmdlet to retrieve a specific site, store a TemplateType in a variable, and then use the Add() method to create a new document library:

PS > $spWeb = Get-SPWeb -Identity http://SPServer
PS > $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
PS > $spWeb.Lists.Add("My Documents","My Doc Library",$listTemplate)

Modifying a Document Library

We can retrieve an existing document library using the GetList() method, just as we did with lists. The only difference is the relative URL used with the method:

PS > $spDocumentLibrary = $spWeb.GetList("My Documents")

Next, we can modify the properties of a document library. If we want to change the Description, we can simply type:

PS > $spDocumentLibrary.Description = “Lots of Documents”

Adding Document Library to Quick Launch is also a simple task when using Windows PowerShell:

PS > $spDocumentLibrary.OnQuickLaunch = "True"

When we’re are done with the updates we use the Update() method to commit the changes.

PS > $spDocumentLibrary.Update()

SharePoint document libraries may have folders to better organize the contents of the library. These folders can be created using the same AddItem() method just as we did when adding new list items. The difference is that we use another overload definition of this method, which also accepts a value of type Microsoft.SharePoint.SPFileSystemObjectType that instructs it whether the new item is a file or a folder:

PS > $spFolder = $spDocumentLibrary.AddItem(
>> "",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,"My New Folder"
PS > $spFolder.Update()
Uploading Files to a Document Library

To upload files to a SharePoint document library, we use the Add method provided by the Microsoft.SharePoint.SPFileCollection class, which represents a collection of SPFile objects in SharePoint 2010.

Before we can access a file collection in SharePoint 2010, we have to create an instance of the Microsoft.SharePoint.SPFolder class using the GetFolder() method provided by the Microsoft.SharePoint.SPWeb class:

PS > $spFolder = $spWeb.GetFolder("My Documents")

After we have bound to the document library, we can store the file collection in a new variable, which we will use to add files:

PS > $spFileCollection = $spFolder.Files

The Add method provided by the Microsoft.SharePoint.SPFileCollection class is used to create a file in a file collection. This is a very versatile method that has 21 overload definitions. For the one that we will be using in our example, we need to specify the file’s relative URL, a byte array containing the file, and a Boolean value that determines whether an existing file with the same name that might already exist should be overwritten. Let’s have a look at the byte array first.

It is possible to expose a sequence of bytes using the System.IO.FileStream class, which we can pass on to the Add method. A simple way of retrieving an object of the type System.IO.FileStream is by using the OpenRead() method provided by the System.IO.FileInfo class. When using the Get-ChildItem cmdlet on a file, we get an object of the type System.IO.FileInfo:

PS > $file = Get-ChildItem C:\Documents\MyDoc.docx

Now we can use the OpenRead() method when adding a new file to a SharePoint library:

PS > $spFileCollection.Add("My Documents/MyDoc.docx",$file.OpenRead(),$false)

The example demonstrates how to upload a single file to a document library in SharePoint 2010. But what if we want to upload multiple files? Simply use the ForEach-Object cmdlet to loop through a collection of files and add them to a SharePoint 2010 document library using the Add() method:

PS > Get-ChildItem C:\Documents -filter “*.docx” | ForEach {
>> $spFileCollection.Add(“My Documents/$($_.Name)”,$_.OpenRead(),$true)

In this post we’ve covered document libraries and uploading files using Windows PowerShell. We’ve seen examples of creating and managing document libraries and how to upload single and multiple files to a document library. The post only touches the surface of what you can do to manage your SharePoint 2010 environment. Be sure to check out PowerShell for Microsoft SharePoint 2010 Administrators for detailed examples about how to create document libraries, manage files, copy files between document libraries, check in and out files, and manage content types.

MK, that is all there is to using Windows PowerShell cmdlets to manage document libraries in SharePoint 2010. And this Guest Blogger Week is done. Our thanks to Niklas Goude for sharing all these exciting posts about SharePoint and Windows PowerShell. Join us tomorrow for Quick-Hits Friday.

We would love you to follow us on Twitter and Facebook. If you have any questions, send email to us at, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.


Ed Wilson and Craig Liebendorfer, Scripting Guys

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Will this work with WSS 3.0 and Sharepoint 2007? It looks like this require scripting knowledge and very different from stsadm. I am just Sharepoint administrator..

    Annd finally can we upload multiple docs like give here

  • Hi,

    The examples in this post will work in SharePoint 2007 with a few minor tweaks. The Cmdlets in SharePoint 2010 are not available in SharePoint 2007 but if you check out this link:

    You'll find alot of scripts that you can use when automating SharePoint 2007. The example in this post uses the Get-SPWeb cmdlet to retrieve a specific Site in SharePoint 2010:

    PS > $spWeb = Get-SPWeb -Identity http://SPServer

    To achieve this in SharePoint 2007 you can either download the "Get-SPWeb.ps1" script from the link above or you can create your own function or script using the followin code:


    $url = "http://yoursite"

    $spSite = New-Object Microsoft.SharePoint.SPSite($url)

    $spWeb = $SPSite.OpenWeb()

    From here you can simply use the code described in the post (with an exception for the AddItem() method.. in SP 2007 you can use Items.Add()instead (note that this approach enumerates the entire SPList.Items collection and can cause performance issues.)

    Also, make sure to set the ThreadOption to "ReuseThread" (PowerShell V2) and dispose of the objects when your done with them.


    Niklas Goude

  • Hey Script Guy,

    This is really a nice article to get started with managing sharepoint lists using PowerShell. I am completely new to powershell. I am a C# developer with knowledge on sharepoint. Can you please tell me how to manage the permissions in a list item like a folder or a file with in sharepoint site with powershell scripting? Also i have written some scripts to add/mange items in a list as discussed above, How can i run these scripts? Does it has to be in the context of the sharepoint or can they be run remotely like on a machine that can connect to a shareppoint site via a browser?


  • Hi Kiran

    Dr Scripto gave me a call and we decided to put together a new post on permissions in SharePoint 2010 (will be posted soon)

    You can run Windows PowerShell remote against a SharePoint server,  this requires that you enable psremoting on yhe sharepoint 2010 server and on the client and set up credssp.

    Jie Li wrote a great step by step blog post that describes how to set up remoting:

  • When I try the example using the foreach loop to upload all docs in a specified folder, I get You cannot call a method on a null-valued expression

  • Hi Script Guy

    Just wondered if you knew when you were going to be publishing the guide on permissions? I've looked at but can't see anything there yet?


  • hi,

    can you help me?

    i have error when run $spFileCollection.Add("report.xls",$file.OpenRead(),$false)

    Exception calling "Add" with "3" argument(s): "Unable to cast COM object of type 'Microsoft.SharePoint.Library.SPRequestInternalClass' to interfa

    ce type 'Microsoft.SharePoint.Library.ISPRequest'. This operation failed because the QueryInterface call on the COM component for the interface w

    ith IID '{BDEADF28-C265-11D0-BCED-00A0C90AB50F}' failed due to the following error: Bad variable type. (Exception from HRESULT: 0x80020008 (DISP_


    At line:1 char:22

    + $spFileCollection.Add <<<< ("report.xls",$file.OpenRead(),$false)

       + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

       + FullyQualifiedErrorId : DotNetMethodException

  • How can this script be modified to download/get a file from SharePoint? In all the powershell examples I have seen - no one has shown how to get a file. Thanks!

  • Thank you.

  • These are solid getting started examples for working with documents in SharePoint with PowerShell. Good stuff.

  • hello PSGurus,

    I am not a sharepoint administrator but I can upload, check in and check out documents to edit them. So, I have contributing rights. I know I can upload and check in document on the sharepoint site. How do I have my script do that for me? The script opens the sharepoint folder as a network drive and copies the documents to it. Then it disconnects the network drive. So, when I go the the sharepoint site I can see the file; however, other team members cannot see the file untill I manually check it in. Is there a way for my script to check it in for me? My sharepoint admin does not support checking in file automatically. So, I am left on my own. If I can check it in myself, there must be a way for the script to check it in with my authentication. Please help. Thanks.


  • How do I update the folders (edited and created) with the same user as in the script below?

    Already tried to insert a $spFolder.Update() - but that fails...

    $spFolder["created"] = $SPFieldUserValue

           $spFolder["Edited"] = $SPFieldUserValue        


    The scipt that work on the items/documents are

    [Reflection.Assembly]::Load("Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

    $SPSite = New-Object Microsoft.SharePoint.SPSite("http://portal/")

    $SPWeb = $SPSite.OpenWeb()

    $SPList = $SPWeb.Lists["Documents"]

    $SPListItemCollection = $SPList.Items

    foreach ($ListItem in $SPListItemCollection)


           $SPFieldUserValue = New-Object Microsoft.SharePoint.SPFieldUserValue($SPWeb,<userid>,"<username>")

    $ListItem["Editor"] = $SPFieldUserValue

           $ListItem["Author"] = $SPFieldUserValue        




  • Any idea how to update the Document Library name in the URL? Changing the Title amends the name, but the name in the URL remains the same.

  • Problems with code - what am I doing wrong - it seems so simple above:

    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary

    $data = Import-Csv "C:\PS_SP_Scripts\WebsSitesAndLists.csv"

    foreach($row in $data)


        Write-Host WebName: $row.WebName WebURL: $row.WebURL WebDescription: $row.WebDescription LibName: $row.LibName LibDescription: $row.LibDescription

        $spWeb = New-SPWeb $row.WebURL -Template "STS#0" -Name $row.WebName -description $row.WebDescription -AddToQuickLaunch -AddToTopNav


    $NewLib = $spWeb.GetList($row.LibName)

        $spFolder = $NewLib.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,"My New Folder")



    WebName: sub0021 WebURL: http://sf-dev-sp1005:49081/sub0021 WebDescription: sub0

    021 LibName: lib001sub0021 LibDescription: lib001sub0021




    Exception calling "GetList" with "1" argument(s): "<nativehr>0x80070002</native


    At line:6 char:30

    +      $NewLib = $spWeb.GetList <<<< ($row.LibName)

       + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

       + FullyQualifiedErrorId : DotNetMethodException

    Method invocation failed because [System.Guid] doesn't contain a method named '


    At line:7 char:33

    +      $spFolder = $NewLib.AddItem <<<< ("",[Microsoft.SharePoint.SPFileSystemO

    bjectType]::Folder,"My New Folder")

       + CategoryInfo          : InvalidOperation: (AddItem:String) [], RuntimeEx


       + FullyQualifiedErrorId : MethodNotFound

    You cannot call a method on a null-valued expression.

    At line:8 char:22

    +      $spFolder.Update <<<< ()

       + CategoryInfo          : InvalidOperation: (Update:String) [], RuntimeExc


       + FullyQualifiedErrorId : InvokeMethodOnNull

  • Found it very useful. Nice work done