Powershell Script to manage document library

Hi,
I would like to write a powershell script that will be run as a job in the task scheduler on a daily basis. The  idea is to delete documents or folders from a particular folder in the document library that are created 30 days ago.
Can anyone help me with this script?

Hi - I think you can perform this OOB using retention policy
http://blogs.msdn.com/b/ecm/archive/2011/10/12/policy-and-retention-in-sharepoint-server-2010.aspx
http://blogs.msdn.com/b/mvpawardprogram/archive/2011/10/03/applying-document-retention-in-sharepoint-2010.aspx
-prs

Similar Messages

  • Powershell Script - Convert Managed Metadata column Value to string

    HI,
    I have written a small PowerShell Script to pull records from a SP List and put them in a csv file. Here is the script:
    $MyWeb = Get-SPWeb "http://dev-apps:8800/applications/PA"
    $MyList = $MyWeb.Lists["Alist"]
    $exportlist = @()
    $Mylist.Items | foreach {
    $obj = New-Object PSObject -Property @{
    “PName” = $_["Port Name"]
    "AName" = $_["Agent Name"]
    "Address 1" = $_["Address 1"]
    "Address 2" = $_["Address 1"]
    "Address 3" = $_["Address 3"]
    "Address 4" = $_["Address 4"]
    $exportlist += $obj
    $exportlist | Export-Csv -path 'C:\Filename.csv'
    The script is running all right, the output file is also created, data is also correct for all columns but 1. This PName is a
    Managed metadata type column and the output values I am getting for this column are like this:
    "ERICA|a6d1e8fd-1f6b-4e09-9830-d21e35950881"
    "CLIVE|24dff17f-a1b5-4abe-ae86-57299e1e098b"
    viz. the ["Actual Value"|"its GUID"] (seems so). I do not want this GUID to be included in the result csv. Is there a way to remove it.
    P.S. Choice column values are being fetched just file.

    Try this (you'll need to add in your other properties)
    $items = New-Object psobject
    $items | Add-Member -MemberType NoteProperty -Name "AName" -value "" ;
    $items | Add-Member -MemberType NoteProperty -Name "PName" -value "" ;
    $items | Add-Member -MemberType NoteProperty -Name "Address1" -value "" ;
    $items | Add-Member -MemberType NoteProperty -Name "Address2" -value "" ;
    $items | Add-Member -MemberType NoteProperty -Name "Address3" -value "";
    $exportlist = @();
    $Mylist.Items | foreach {
    $pname = $_["PName"] -as [Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue];
    $obj = $items | Select-Object *;
    $obj.AName = $_["AName"];
    $obj.PName = $pname.Label;
    $obj.Address1 = $_["Address 1"];
    $obj.Address2 = $_["Address 2"];
    $obj.Address3 = $_["Address 3"];
    $exportlist += $obj
    $exportlist | Export-Csv -path 'C:\AData.csv'
    Regards, Matthew
    MCPD | MCITP
    My Blog
    View
    Matthew Yarlett's profile
    See my webpart on the TechNet Gallery that allows administrative users to upload, crop and format user profile photos. Check it out here:
    Upload and Crop User Profile Photos

  • Looking for help with PowerShell script to delete folders in a Document Library

    I'd like to create a PowerShell script to delete old folders in a Document library that are over 30 days old. Has anyone created something like this?
    Orange County District Attorney

    Hello Sid:
    I am trying to do the same and Iam running the script to delete the subfolders inside a folder  but I have some errors. 
    Could you please take a look?
    _______Script________
    $web = Get-SPWeb -Identity https://myportal.mydomain.com
    $list = $web.GetList("ar_mailingactivity")
    $query =  New-Object Microsoft.SharePoint.SPQuery 
    $camlQuery = '<Where><And><Eq><FieldRef Name="ContentType" /><Value Type="Computed">Folder</Value></Eq><Leq><FieldRef Name="Created" /><Value Type="DateTime"><Today OffsetDays="-30" /></Value></Leq></And></Where>'
    $query.Query = $camlQuery
    $items = $list.GetItems($query)
    for ($intIndex = $items.Count - 1; $intIndex -gt -1; $intIndex--)
       $items.Delete($intIndex);
    ________Errors_______
    Unable to index into an object of type System.Management.Automation.PSMethod.
    At C:\Script.ps1:2 char:22
    + $list =$webGetList <<<< "ar_mailingactivity"]
    + CategoryInfo
    :InvalidOperation: (ar_mailingactivity:String) [], RuntimeException
    + FullyQualifiedErrorID
    :CannotIndex
    You cannot call a method on  a null-valued expression.
    At c:\Script.ps1:6 char:24
    + $items = $list.GetItems <<<< ($query)
    + CategoryInfo
    :InvalidOperation: (GetItems:String) [], RuntimeException
    + FullyQualifiedErrorID
    :InvokeMethodOnNull

  • Powershell Script to create "custom" Document Library

    I have a powershell script which creates a Document Library for every user in AD.
    This works, but rather than using the default Document Library I want it use a custom Document Library.  However this isnt working.
    My script to create the default Document Library is this...
    [System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
    $site = new-object Microsoft.SharePoint.SPSite("http://servername/sitename");
    $siteweb = $site.OpenWeb();
    $webs = $siteweb.Webs;
    $strFilter = "(&(objectCategory=User)(name=accountname))"
    $objDomain = New-Object System.DirectoryServices.DirectoryEntry
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"
    $colProplist = "samaccountname"
    foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
    $colResults = $objSearcher.FindAll()
    foreach ($objResult in $colResults)
    $objItem = $objResult.Properties; $objItem.samaccountname
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
    $listId = $siteweb.Lists.Add($objItem.samaccountname, "", $listtemplate);
    $list = $siteweb.Lists.GetList($listId, $true);
    $roleDef = $siteweb.RoleDefinitions.GetByType("Contributor");
    $user = "domain\" + $objItem.samaccountname;
    $rolAssign = new-object Microsoft.SharePoint.SPRoleAssignment($user, "email", "name", "notes");
    $rolAssign.RoleDefinitionBindings.Add($roleDef);
    if(!$list.HasUniqueRoleAssignments)
    {$list.BreakRoleInheritance($true);}
    for ($i = $list.roleAssignments.Count - 1; $i -gt -1; $i--)
    { $list.RoleAssignments.Remove($i) }
    $list.RoleAssignments.Add($rolAssign);
    $list.Update();
    Now I have a custom Document Library named "TESTLIB" so if I substitute the line:
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
    with
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::TESTLIB
    Then it errors with this...
    How can I script powershell to create a "custom" Document Library?
    Thanks

    The below link should help you in creating custom document library using powershell
    http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/23/use-powershell-cmdlets-to-manage-sharepoint-document-libraries.aspx
    Vinod H
    Thanks for the link but I cant see anything to assist creating a custom library?  Was there something in paticular you saw?

  • Save output of powershell script to a SharePoint document library?

    Hi
    I've got the PS script below which scripts out our SQL replication so disaster recovery.  Is there a way to output this to a SharePoint document library so that way we can version control the file to keep multiple copies and it also avoids outputting
    this to a file share.  We would still need to have the files with the .sql extension format which is an allowed file type in our farm.
    Thanks
    #Load command-line parameters - if they exist
    param ([string]$sqlserver, [string]$filename)
    #Reference RMO Assembly
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Replication") | out-null
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Rmo") | out-null
    function errorhandler([string]$errormsg)
        writetofile ("-- Replication Script Generator run at: " + (date)) $filename 1
        writetofile ("-- [Replication Script ERROR] " + $errormsg) $filename 0
    function writetofile([string]$text, [string]$myfilename, [int]$cr_prefix)
        if ($cr_prefix -eq 1) { "" >> $myfilename }
        $text >> $myfilename
    function initializefile([string]$myfilename)
        "" > $myfilename
    trap {errorhandler($_); Break}
    #Deal with absent parameters
    [string] $hostname=hostname
    if ($sqlserver -eq "") {$sqlserver = read-host -prompt "Please enter the server name or leave blank for Hostname"}
    #if ($filename -eq "")  {$filename = read-host -prompt "Please enter the file name (eg 'c:\ReplicationBackupScript.sql')..."}
    if ($sqlserver -eq "")   {$sqlserver = $hostname}
    if ($filename -eq "")   {$filename = "d:\Rep\CreateReplication-$(get-date -format ddMMyyyy).sql"}
    # Clear file contents
    if (Test-Path  ($filename)) {Clear-Content $filename}
    $repsvr=New-Object "Microsoft.SqlServer.Replication.ReplicationServer" $sqlserver
    initializefile $filename
    # if we don't have any replicated databases then there's no point in carrying on
    if ($repsvr.ReplicationDatabases.Count -eq 0)
        writetofile ("-- Replication Script Generator run at: " + (date)) $filename 0
        writetofile "-- ZERO replicated databases on $sqlserver!!!" $filename 1
        EXIT
    # similarly, if we don't have any publications then there's no point in carrying on
    [int] $Count_Tran_Pub = 0
    [int] $Count_Merge_Pub = 0
    foreach($replicateddatabase in $repsvr.ReplicationDatabases)
            $Count_Tran_Pub = $Count_Tran_Pub + $replicateddatabase.TransPublications.Count
            $Count_Merge_Pub = $Count_Merge_Pub + $replicateddatabase.MergePublications.Count
    if (($Count_Tran_Pub + $Count_Merge_Pub) -eq 0)
        writetofile ("-- Replication Script Generator run at: " + (date)) $filename 0
        writetofile "-- ZERO Publications on $sqlserver!!!" $filename 1
        EXIT
    # if we got this far we know that there are some publications so we'll script them out
    # the $scriptargs controls exactly what the script contains
    # for a full list of the $scriptargs see the end of this script
    $scriptargs = [Microsoft.SqlServer.Replication.scriptoptions]::Creation `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeEnableReplicationDB `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeCreateLogreaderAgent `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludePublicationAccesses `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeArticles `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludePublisherSideSubscriptions `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeSubscriberSideSubscriptions
    writetofile ("-- Replication Script Generator run at: " + (date)) $filename 0
    writetofile "-- PUBLICATIONS ON $sqlserver" $filename 1
    writetofile "-- TRANSACTIONAL PUBLICATIONS ($Count_Tran_Pub)" $filename 1
    foreach($replicateddatabase in $repsvr.ReplicationDatabases)
        if ($replicateddatabase.TransPublications.Count -gt 0)
            foreach($tranpub in $replicateddatabase.TransPublications)
                writetofile "/********************************************************************************" $filename 0
                writetofile ("***** Writing to file script for publication: " + $tranpub.Name) $filename 0
                writetofile "********************************************************************************/" $filename 0
                [string] $myscript=$tranpub.script($scriptargs) 
                writetofile $myscript $filename 0
    writetofile "-- MERGE PUBLICATIONS ($Count_Merge_Pub)" $filename 1
    foreach($replicateddatabase in $repsvr.ReplicationDatabases)
        if ($replicateddatabase.MergePublications.Count -gt 0)
            foreach($mergepub in $replicateddatabase.MergePublications)
                writetofile "/********************************************************************************" $filename 0
                writetofile ("***** Writing to file script for publication: " + $mergepub.Name) $filename 0
                writetofile "********************************************************************************/" $filename 0
                [string] $myscript=$mergepub.script($scriptargs) 
                writetofile $myscript $filename 0

    Check out Using PowerShell to upload a scripts output to SharePoint
    Jason Warren
    @jaspnwarren
    jasonwarren.ca
    habaneroconsulting.com/Insights

  • How to update managed metadata column for all file in document library using powershell

    Hi,
    How to update managed metadata column for all file in document library using powershell?
    Any help on it.
    Thanks & REgards
    Poomani Sankaran

    Hi TanPart,
    I have changed the code which you have give in order to get the files from SharePoint 2010 Foundation  Document Library.But i am getting below error in powershell.
    Property 'ListItemCollectionPosition' cannot be found on this object; make sure it exists and is settable.
    Could you tell me which is the issues in it?
    See the code below.
    $web = Get-SPWeb http://ntmoss2010:9090/Site
    $list = $web.Lists["DocLib"]
    $query = New-Object Microsoft.SharePoint.SPQuery
    $query.ViewAttributes = "Scope='Recursive'";
    $query.RowLimit = 2000
    $caml = '<Where><Contains><FieldRef Name="Title" /><Value Type="Text">Process Documents/Delivery</Value></Contains></Where>' +
            '<OrderBy Override="TRUE"><FieldRef Name="ID"/></OrderBy>'
    $query.Query = $caml
    do
        $listItems = $list.GetItems($query)
        $spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
        foreach($item in $listItems)
            #Cast to SPListItem to avoid ambiguous overload error
            $spItem = [Microsoft.SharePoint.SPListItem]$item;
            Write-Host $spItem.Title       
    while ($spQuery.ListItemCollectionPosition -ne $null)
    Thanks & Regards
    Poomani Sankaran

  • Enable document management for entities through PowerShell script (Dynamic CRM 2013 on premises)

    Hello,
    Can anybody let me know if it is possible to enable document management for entities through PowerShell script for Dynamic CRM 2013 on premises.
    I want power shall script where user will give the entity (Accounts, Contacts etc.)   for the CRM.
    The script should enable the document management for the entity.
    Thank you for your support.

    Hi Jeff,
    Any updates? If you have any other questions, please feel free to let me know.
    A little clarification to the script:
    function _ErrObject{
    Param($name,
    $errStatus
    If(!$err){
    Write-Host "error detected"
    $script:err = $True
    $ErrObject = New-Object -TypeName PSObject
    $Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
    $Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
    $script:ErrOutput += $ErrObject
    $errOutput = @()
    _ErrObject Name, "Missing External Email Address"
    $errOutput
    _ErrObject Name "Missing External Email Address"
    $errOutput
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

  • PowerShell script to find and remove duplicate items from document library

    Hi Friends,
    Please check this below script, It is finding the duplicate items and removing it. This script is not working to find the duplicate items from document
    library and remove. Can you please let me know where it is wrong.
    Add-PSSnapin microsoft.sharepoint.powershell 
    $web = Get-SPWeb -Identity "http://zapltvsspdev02:4333/bu/EXCO" 
    $list = $web.Lists["AECI Documents"] 
    $AllDuplicates = $list.Items.GetDataTable() | Group-Object INumber | where {$_.count -gt 1} 
    $count = 1 
    $max = $AllDuplicates.Count 
    foreach($duplicate in $AllDuplicates) 
    $duplicate.group | Select-Object -Skip 1 | % {$list.GetItemById($_.ID).Delete()} 
    Write-Progress -PercentComplete ($count / $max * 100) -Activity "$count duplicates removed" -Status "In Progress" 
    $count++ 
    Remove-PsSnapin Microsoft.SharePoint.PowerShell
    Note:
    In the above code, duplicates are found using the "INumber" column. 
    valmiki

    check this
    http://stackoverflow.com/questions/21337158/delete-duplicate-items-in-sharepoint-list

  • Update document library item where a docx document uploaded using powershell script

    HI
    when i update an existing item of a document library using script i faced the issue.
    i uploaded two .txt files and two word docx files and a png file.
    where i update .txt file item there is no issues , but  for other items i have problem.
    PS C:\Scripts> C:\Scripts\UPdateDocLibrary.ps1
    Exception calling "Update" with "0" argument(s): "There is no file with URL 'Do
    cs/Emc.docx' in this Web."
    At C:\Scripts\UPdateDocLibrary.ps1:26 char:13
    + $item.Update <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException
    Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
    $webURL = "http://tspmcwfe:89"
    $listName = "Docs"
    #Get the SPWeb object and save it to a variable
    $web = Get-SPWeb $webURL
    #Get the SPList object to retrieve the "Demo List"
    $list = $web.Lists[$listName]
    $items = $list.items
    #Go through all items
    foreach($item in $items)
    if($item["NO"] -eq $null)
    $item["Title"] = "My updated edited item!"
    $item.Update()
    adil

    Please check if file is checkout or locked , and if not then checkout it and then try to update -
    $url= $webURL + $item.File.Url;
    $file = $web.GetFile($url);
    if($file.CheckOutType -eq "None" -And $file.LockType -eq "None")
    $file.CheckOut();
    also please try these option, may help -
    1. Allow unsafe update at web
    $web.AllowUnsafeUpdates=$true;
    2. try systemupdate
    $item.SystemUpdate($false)
    Thanks
    Ganesh Jat [My Blog |
    LinkedIn | Twitter ]
    Please click 'Mark As Answer' if a post solves your problem or 'Vote As Helpful' if it was useful.

  • PowerShell script to update ContentType of existing records in Document Library

    we are using Document Library in SharePoint 2010 environment. there are about 200 document
    present in the document library which have been identified (based on location - England and employee type - FT) and now i have to change the content type of these 200 documents to a new content type 'New FT'. I'm using the below power shell code for the purpose
    $webUrl = "http://www.site.com/sites/Library/"
    $web = Get-SPWeb -Identity $webUrl
    $list = $web.Lists["CURRENT FTE"]
    $spQuery = New-Object Microsoft.SharePoint.SPQuery
    $spQuery.ViewAttributes = "Scope='Recursive'";
    $spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
    foreach($item in $listItems)
    $lookup = [Microsoft.SharePoint.SPFieldLookupValue]$item["ROLE"];
    $role = $lookup.LookupValue;
    $EMPTYPE = $item["EMP TYPE"]
    $lookup4 = [Microsoft.SharePoint.SPFieldLookupValue]$item["Location"];
    $LOCATION = $lookup4.LookupValue;
    $ContentTypeName = $item.ContentType.Name
    $ContentTypeID = $item.ContentType.Id
    if ($LOCATION -eq "England")
    if($EMPTYPE -eq "FT")
    #CheckList - 1
    Write-Output "ID - $($item.id) "
    Write-Output "Name - $($item.name)"
    Write-Output "Role - $($role) "
    Write-Output "emptype - $($EMPTYPE) "
    Write-Output "location - $($LOCATION) "
    Write-Output "Content Type Name - $($ContentTypeName) "
    Write-Output "Content Type ID - $($ContentTypeID) "
    Write-Output " "
    $newct = $list.ContentTypes["New FT"]
    $newctid = $newct.ID
    If (($newct -ne $null) -and ($newctid -ne $null))
    $item["ContentTypeId"] = $newctid
    $item.Update()
    $newContentTypeName = $item.ContentType.Name
    $newContentTypeID = $item.ContentType.Id
    #CheckList - 2
    Write-Output "ID - $($item.id) "
    Write-Output "Name - $($item.name)"
    Write-Output "Role - $($role) "
    Write-Output "emptype - $($EMPTYPE) "
    Write-Output "location - $($LOCATION) "
    Write-Output "Content Type Name - $($newContentTypeName) "
    Write-Output "Content Type ID - $($newContentTypeID) "
    Write-Output " "
    Now the code identifies each document/record and then prints the details as listed on CheckList - 1, then i do an update and try to print the new updated values in CheckList
    - 2 - but the problem is the CheckList -2 doesn't print the updated content type and updated content type ID ($newContentTypeName, $newContentTypeID).
    Am i doing some thing wrong here , Please advise ! (feel free to update the code if necessary)

    Hi,
    I suggest you consider the Check Out status of these documents before change the content type.
    You can take the code from the link below for a test in your environment:
    http://get-spscripts.com/2010/10/change-content-type-set-on-files-in.html       
    Best regards
    Patrick Liang
    TechNet Community Support

  • Powershell script to change the a column value of all documents in a site.

    Hi,
    I need a powershell script to change the value of a column (a site column which has been added to all document libraries) in all documents in a site,
    For example: 
    -column 1 is a site column added to all libraries
    the value of column 1 of all documents under this site: http://intranet.doman/ex1 should be equal to V1
    the value of column 1 of all documents under this site: http://intranet.doman/ex2 should be equal to V2
    So, if I can write a powershell script to change the value of all documents in a site, I can modify it for different site that I have and run it for each of them individually,

    cls
    # Is dev version?
    $dev = $false
    # Configuration
    $termStore = "Managed Metadata Service"
    $group = "G1"
    $subjectMatterTermSetName = "Subject Matter"
    # Check if SharePoint Snapin is loaded
    if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
         Add-PSSnapin Microsoft.SharePoint.PowerShell
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy") | Out-Null
    function GetTermStore($site, $termStore, $group, $termSet) {    
        $session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
        $termStore = $session.TermStores[$termStore]
        $group = $termStore.Groups[$group]
        $termSet = $group.TermSets[$termSet]
        return $termSet
    if($dev) {
        Write-Host "Running DEV version..."
        $webUrl = "http://Site1"   
        $libraryName = "L1"
        $subjectMatter = "C1"
    } else {
        $webUrl = Read-Host "Enter Site URL" 
        $libraryName = Read-Host "Enter Document Library name"
    $subjectMatter = Read-Host "Enter Subject Matter"
    try {
        $web = Get-SPWeb $webUrl
        $site = $web.Site
        $library = $web.Lists[$libraryName]
        $items = $library.GetItems()
        $subjectMatterTermSet = GetTermStore $site $termStore $group $subjectMatterTermSetName
        $subjectMatterTerm = $subjectMatterTermSet.GetTerms($subjectMatter,$true) | select -First 1
        foreach($item in $items) {
            if([string]::IsNullOrEmpty($item["Subject Matter"])) {     
                #Write-Host "Filename: $filename / Keywords: $keywords / Subject Matter: $subjectMatter / Document Type: $documentType"        
                Write-Host "Updating $($item["ows_FileLeafRef"])..."           
                # Set Subject Matter column
                $subjectMatterField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$item.Fields["Subject Matter"]
                $subjectMatterField.SetFieldValue($item,$subjectMatterTerm)
                # Update Item
                $item.SystemUpdate()
    catch
        $ErrorMessage = $_.Exception.Message
        Write-Host "Something went wrong. Error: $ErrorMessage" -ForegroundColor Red

  • Calling Recursive function with Powershell to list all documents in the document library under a SIte collection

     function Recurse($RootFolder,$List) {
                            $Context.Load($RootFolder)
                            $Context.Load($RootFolder.Folders)
                            $Context.ExecuteQuery()
                            foreach($folder in $RootFolder.Folders)
                                if($Folder.Name -ne "Forms")
                                        $Context.Load($folder)
                                        $Context.Load($folder.Files)
                                        $Context.ExecuteQuery()
                                        foreach($file in $folder.Files)
                                            $FileCollection +=
    $file
                                        Recurse $folder $List 
                                Recurse $folder.ParentFolder $List
                                Return $FileCollection
    I am trying to traverse through SharePoint Online Site collection using Powershell CSOM. I am able to go to the last folder from the root folder which is 2-3 levels down. But I could not search through all the document libraries as it gets struck to one
    of the last document library.

    Below script is working for me. I can now traverse through all the folders and subfolders including the root folders to fetch all the files using Powershell and CSOM.
    #function begins
                        function Recurse($RootFolder) {
                            $Context.Load($RootFolder)
                            $Context.Load($RootFolder.Folders)
                            $Context.ExecuteQuery()
                            $Context.Load($RootFolder.Files)
                            $Context.ExecuteQuery()
                            $resultCollection = @()
                            foreach($file in $RootFolder.Files)
                                $resultCollection += $file
                            foreach($folder in $RootFolder.Folders)
                                if($Folder.Name -ne "Forms")
                                   Recurse $folder  
                                Return $resultCollection
                        # Function ends

  • Get/retreive managed metadata column value from Document Library using SharePoint 2013 JSOM

    Hi,
    I am trying to retrieve managed metadata column (NewsCategory) value in SharePoint 2013 Document library using JSOM.
    I get "Object Object" rather than actual value.
    I tried:-
    var newsCat = item.get_item('NewsCategory');
    alert(newsCat) //Displays [Object Object]
    var newsCatLabel = newsCat.get_label();
    var newsCatId = newsCat.get_termGuid();
    But, I get the error "Object doesn't support property or method get_label()"
    I also tried :-
    var newsTags = item.get_item(' NewsCategory ');
    for (var i = 0; i < newsTags.get_count() ; i++) {
    var newsTag = newsTags.getItemAtIndex(i);
    var newsTagLabel = newsTag.get_label();
    var newsTagId = newsTag.get_termGuid();
    Even now I get the error "Object doesn't support property or method get_count()"
    I have included " NewsCategory " in the load request:- context.load(items, 'Include(File, NewsCategory)');
    Any idea what the issue is? Do I have to add any *.js file using $.getScript?
    I added following .js files
    var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.Runtime.js", function () {
    $.getScript(scriptbase + "SP.js", function () {
    $.getScript(scriptbase + "SP.Core.js", function () {
    Thanks in Advance,

    Hi Patrick,
    I already added those references. I just pasted the parts of script snippet in my initial post. To avoid confusion I am pasting here complete script.
    2.1.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.Runtime.js", function () {
    $.getScript(scriptbase + "SP.js", function () {
    $.getScript(scriptbase + "SP.Core.js", function () {
    function getdata() {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle('Documents');
    var camlQuery = new SP.CamlQuery();
    var filterCategory = 'Solutions';
    var IDfromTaxonomyHiddenList = 15;
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef LookupId="TRUE" Name="'+filterCategory+'" /><Value Type="ID">' + IDfromTaxonomyHiddenList +'</Value></Eq></Where></Query></View>');
    /*the above CAML query successfully gets all the list items matching the criteria including "NewsCategory" managed metadata column values
    But when I try to display the value it retrieved it ouputs/emits Object Object rather than actual values */
    var items = list.getItems(camlQuery);
    context.load(items, 'Include(File,NewsCategory)');
    context.executeQueryAsync(
    Function.createDelegate(this, function (sender, args) {
    if (items.get_count() > 0) {
    var listItemEnumerator = items.getEnumerator();
    while (listItemEnumerator.moveNext()) {
    var oListItem = listItemEnumerator.get_current();
    var file = oListItem.get_file();
    var name = file.get_name();
    var newsCat = oListItem.get_item('NewsCategory'); alert(newsTags.constructor.getName());
    alert(newsCat) //Displays [Object Object]
    var newsCatLabel = newsCat.get_label(); // Here it errors out with message "Object doesn't support property or method get_label()"
    var newsCatId = newsCat.get_termGuid();
    } //end while
    }//end if
    Function.createDelegate(this, function (sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    ExecuteOrDelayUntilScriptLoaded(getdata, "SP.Core.js");
    </script>
    In the above script "var name = file.get_name(); " gets the exact file name.
    But the line "var newsCat = item.get_item('NewsCategory');
           alert(newsCat) //Displays [Object Object]  rather than actual value.
    Issue resolved replace "oListItem.get_item('NewsCategory');" with oListItem.get_item('NewsCategory').get_label();"
    Thanks

  • Sharepoint 2010 -Script to get file name from Document Library

    Hi 
    can anybody send be script that works in "SharePoint 2010 management Shell" to get list of file names in document library.
    Thank

    See my updated answer. The double quotes need to be removed. Also note that you need to use $item.File.Name
    and not $item.Name to get the name of the files.
    Blog | SharePoint Learnings CodePlex Tools |
    Export Version History To Excel |
    Autocomplete Lookup Field

  • PowerShell Script for Setting the Welcome Page View of a document set

    Hi,
    We are using document set in the document library and we have created the separate view in the document set and it will show only particular metadata columns. We need to change from default view to another view. For this, we need to write the power shell
    script and update the document set welcome page view link in the document set template. Please let me know how we can get this.
    Thanks,
    Mylsamy

    Hey Mylsamy,
    welcome page view is stored in $contenttype.XmlDocuments. Here is how you can change the view using powershell:
    $web = Get-SPWeb "WEBURL"
    $list = $web.Lists["LISTNAME"]
    $contenttype = $list.ContentTypes["CONTENTYPENAME"]
    $viewid = $list.Views["VIEWNAME"].Id
    $xmldocs = $contenttype.XmlDocuments
    foreach($xmldoc in $xmldocs)
    if($xmldoc.Contains("WelcomePageView"))
    Write-Host "XML contains WPV"
    $newview = [XML] @"
    <wpv:WelcomePageView xmlns:wpv="http://schemas.microsoft.com/office/documentsets/welcomepageview" ViewId="$viewid" />
    $xmldocs.Delete("http://schemas.microsoft.com/office/documentsets/welcomepageview")
    $xmldocs.Add($newview)
    break;
    $contenttype.Update($updateChildren, $false)
    Write-Host "Welcome Page View updated at " $list.Title
    Regards,
    Alexander 

Maybe you are looking for