Use PowerShell Cmdlets to Manage SharePoint Document Libraries


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:DocumentsMyDoc.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

Comments (31)

  1. Anonymous says:

    I've been using this a lot to upload documents to SharePoint over the last year, it has been great for migrating File Shares to SharePoint. We'll start by using a Get-ChildItem command to list all the files recursively to a CSV, then apply metadata to the spreadsheet, and then using PowerShell to upload and tag the documents.

    Recently I've had a requirment to upload documents from a file share and check the file share on a weekly basis for changes. When new document are on the share, they get uploaded to SharePoint. Now they want documents that have been updated in the file share to be uploaded to SharePoint as a new version. I haven't been able to find code that will add a new version to an existing document.

    The file share is part of other business processes so just taking that out of the equation is not an option today.

  2. Anonymous says:

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

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

    $data = Import-Csv "C:PS_SP_ScriptsWebsSitesAndLists.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

  3. Does anyone know if you can set up a sharepoint document library as a PSdrive?  Or if you can get powershell to access a file out of a document library?

  4. Found it very useful. Nice work done

  5. Anonymous says:

    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!

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

  7. mredwilson says:

    @Arun I am glad you found the article. Niklas Goude is a great guest, and his articles are always well received. In fact, this coming week we have an entire week written by him. Please be sure to check them out.

  8. Nice work guys.  Thanks for posting and explaininng these so well.

  9. I got an error when running this script, and I found out that I used a backslash instead of a forward slash (as in the example).

    Then I found out that "Documents" is not need in the path because this is stored in the variabel $spFolder.

    Running the command again with backslash instead of forward slash (as in the example) gives this error:

    PS C:Usersadministrator.FILOBIT.000> $spFileCollection.Add("DocumentsMCP-tips _Eng.doc",$file.OpenRead(),$false) Exception calling "Add" with "3" argument(s): "0x80070003< nativestack="">There is no file with URL 'http://intranet/Documents/ Documents/MCP-tips_Eng.doc' in this Web." At line:1 char:1 + $spFileCollection.Add("DocumentsMCP-tips_Eng.doc",$file.OpenRead(),$false) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DirectoryNotFoundException

    Running the command again without "Documents" in the path specified: *****************************************************************************

    PS C:Usersadministrator.FILOBIT.000> $spFileCollection.Add("MCP-tips_Eng.doc", $file.OpenRead(),$false)

    This is because we store the name of folder in this variabel: ***************************************************************
    $spFolder = $spWeb.GetFolder("Documents")

  10. Sar says:

    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

  11. Niklas Goude says:


    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&quot;

    $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

  12. Kiran says:

    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?


  13. Niklas Goude says:

    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:

  14. Vince says:

    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

  15. Alastair Weller says:

    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?


  16. iovan says:


    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

  17. exactly what I am looking says:

    Thank you.

  18. AJ says:

    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.


  19. Wiper says:

    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/&quot😉

    $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        




  20. Dave D says:

    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.

  21. Dave Nicholls says:

    I would like to create a new Document Library in all our users "My Sites"...

    I've tried using "$spWeb.Lists.Add" but I get an access denied error - the path I'm trying to create the document libray in is "".
     Any ideas on how I could create the document library across all users.


  22. KellyK says:

    It appears that you can't edit Managed Metadata fields in a Document Library, but you can in a Library (ex. Change the value of a Managed Metadata field from "Location 1" to "Location 2". Any ideas on why this is limited?

  23. I got an error when running this script, and I found out that I used a backslash instead of a forward slash (as in the example). Then I found out that "Documents" is not need in the path because this is stored in the variabel $spFolder. ****************************************************************************
    Running the command again with backslash instead of forward slash (as in the example) gives this error: ***************************************************************************** PS C:Usersadministrator.FILOBIT.000> $spFileCollection.Add("DocumentsMCP-tips
    _Eng.doc",$file.OpenRead(),$false) Exception calling "Add" with "3" argument(s): "0x80070003< nativestack>There is no file with URL 'http://intranet/Documents/ Documents/MCP-tips_Eng.doc' in this Web." At line:1 char:1 + $spFileCollection.Add("DocumentsMCP-tips_Eng.doc",$file.OpenRead(),$false)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DirectoryNotFoundException ****************************************************************************
    Running the command again without "Documents" in the path specified: ***************************************************************************** PS C:Usersadministrator.FILOBIT.000> $spFileCollection.Add("MCP-tips_Eng.doc", $file.OpenRead(),$false) **************************************************************
    This is because we store the name of folder in this variabel: *************************************************************** $spFolder = $spWeb.GetFolder("Documents")

  24. Chris says:

    What about deleting a document library and list.

  25. Chris says:

    what about deleting a document library.

  26. Jakub Žižka says:

    This does not work:
    $spDocumentLibrary = $spWeb.GetList("My Documents")

    $spDocumentLibrary = $spWeb.Lists("My Documents")

  27. Venkatesh says:

    I can't find Get -SPWeb cmdlet.

  28. TCSPSADM says:

    how would we pass credentials, like as we would have security on the document library

  29. Error Settings The term Settings is not says:

    Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue
    Settings for the destination to create documents in
    set-ExecutionPolicy Unrestricted or set-ExecutionPolicy AllSigned

    # Settings for the destination to create documents in
    $webUrl = " Department/Staff Development Student Sup/FireSafety"
    $docLibraryName = "/My Department/Staff Development Student Sup/FireSafety/FSP PDF"
    $spWeb = Get-SPWeb -Identity $webUrl
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
    $listtmp=" Department/Staff Development Student Sup/FireSafety/FSP PDF"
    # $list = $spweb.Lists.[$docLibraryName]

    $list=Get-SPList -Identity $listtmp

    Settings : The term 'Settings' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or

    if a path was included, verify that the path is correct and try again.
    At line:2 char:1
    + Settings for the destination to create documents in
    + ~~~~~~~~
    + CategoryInfo : ObjectNotFound: (Settings:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    Set-ExecutionPolicy : Cannot bind parameter 'Scope'. Cannot convert value "or" to type "Microsoft.PowerShell.ExecutionPolicyScope". Error: "Unable to

    match the identifier name or to a valid enumerator name. Specify one of the following enumerator names and try again: Process, CurrentUser,

    LocalMachine, UserPolicy, MachinePolicy"
    At line:3 char:34
    + set-ExecutionPolicy Unrestricted or set-ExecutionPolicy AllSigned
    + ~~
    + CategoryInfo : InvalidArgument: (:) [Set-ExecutionPolicy], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

  30. Hank says:

    When I try this in my environment I get the following error:

    Exception calling "Update" with "0" argument(s): "This operation can only be performed on a file; "" is a folder."

    Thanks in advance.

Skip to main content