SharePoint Online Iterating through Document Libraries CSOM

Hi,
I am trying to iterate though a document library and set each document/items whithin to inherit permissions (at the moment each doc/item is using uniquer permissions).
I am able to get the specific document library that I am interesting in, however I cannot at the moment iterate though each of the items/documents within it, but here is what I have so far:
Add-Type -Path "Libraries\Microsoft.SharePoint.Client.dll"
Add-Type -Path "Libraries\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "Libraries\Microsoft.SharePoint.Linq.dll"
Add-Type -Path "Libraries\Microsoft.SharePoint.dll"
$webUrl = "https://test.sharepoint.com/sites/testsite"
$username = "####"
$password = "####"
$securePass = ConvertTo-SecureString $password -AsPlainText -Force
$listname = "TestDoc";
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePass)
#variables
$web = $ctx.Web
$lists = $web.Lists
$ctx.Load($lists)
$ctx.Load($web)
$ctx.ExecuteQuery()
#print web URL
write-host `n "Web Url:" `n $web.Url
foreach ($list in $lists)
if ($list.Title -eq "TestDoc")
#print list name if found
write-host `n "Found the list:" `n $list.Title `n
#attempting to iterate through items in the document library
foreach ($item2 in $list.Items)
#list the items/documents in the document library
write-host $item2.Title
It is the foreach loop I am having trouble at the moment as I am not sure how to loop though each of the items/documents in the document library.
Any suggestions on the approach I should take would be much appreciated.

Thanks for the heads up, I have re-worked my script which is simpler and now works like a charm:
Add-Type -Path "Libraries\Microsoft.SharePoint.Client.dll"
Add-Type -Path "Libraries\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "Libraries\Microsoft.SharePoint.Linq.dll"
Add-Type -Path "Libraries\Microsoft.SharePoint.dll"
$webUrl = "https://test.sharepoint.com/sites/testsite"
$username = "####"
$password = "####"
$securePass = ConvertTo-SecureString $password -AsPlainText -Force
$listname = "TestDoc"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePass)
#get the List/DocLib and load it for use
$listUpdate = $ctx.Web.Lists.GetByTitle($listname)
$ctx.Load($listUpdate)
$ctx.ExecuteQuery()
#CAML Query to get all items inclusing sub-folders
$spQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
$spQuery.ViewXml = "<View Scope='RecursiveAll' />";
$itemki = $listUpdate.GetItems($spQuery)
$ctx.Load($itemki)
$ctx.ExecuteQuery()
#iterating through the items and reseting permission inheritence
for($j=0; $j -lt $itemki.Count; $j++)
$itemki[$j].ResetRoleInheritance()
$ctx.ExecuteQuery()

Similar Messages

  • Access SharePoint Online Data through code/powershell

    Hi All,<o:p></o:p>
    I need to access SharePoint Online site to upload documents from local machine to the doc libraries on the site.. (100s of docs)
    I am trying to see if I can use PowerShell script for this..  However, I see that SharePoint Online Management Shell cmdlets are not robust enough to do such operations..  Is there a way I can use CSOM / .net console app / any other way.. I am drawing
    blank here.. L<o:p></o:p>
    Any help is much appreciated.<o:p></o:p>
    Charan

    You can start from here
    http://blogs.technet.com/b/fromthefield/archive/2014/02/19/office365-script-to-upload-files-to-a-document-library-using-csom.aspx
    Regards Chen V [MCTS SharePoint 2010]

  • Sharepoint Online Lookup as Document Property for Word Quick Parts

    I'm trying to use Word Quick Parts and the document properties determined by my Sharepoint metadata to automatically fill in portions of the document I'm creating.  Then, I have templates for my company's documents that I'd like to use Quick Parts to
    populate.
    For example, I'd like to choose a project number from another list, and then have Sharepoint look up the associated project's name, address, etc. (I have Sharepoint doing this by means of lookups). Then, the Word template uses Quick Parts to automatically
    fill in information in the document, like the project number. The issue is that I am unable to get Word to allow the use of the lookup information - project name, address, etc. which are associated with the selected job number.
    I currently have the document library set up to select the project number from a lookup of another list. Then it displays the associated project name, address, etc. based on this lookup. I am aware that these columns are merely displayed and nt actually
    populated with metadata, but I have not been successful in using workflows to actually populate this metadata.
    Any help would be greatly appreciated!

    I was able to do something similar with a workflow, but it didn't work out great. For instance, I would select a Project Number from a list, then I would save the document. That would kick off a workflow that would fill in the project description. I would
    have prefered the Project Description to be filled without having to save the document. 
    A separate issue I am seeing is (not with me, but other users) when they select a Project Number from a list, the index number of the Project shows in the document, not the Project Number. When the document gets saved, the Project Number gets saved in the
    metadata. Not sure if this is a permissions issue, but I have tried granting other users full control, and they still experience this issue.

  • Powershell CSOM Sharepoint online list permission

    I've been writing a script to connect to SharePoint online, create a document library and add some AD accounts to the permission. I've written all the code using snippets I have found through many searches but am having an issue with the permissions part.
    All of the code is taken from this page:
    http://jeffreypaarhuis.com/2012/06/07/scripting-sharepoint-online-with-powershell-using-client-object-model/
    The only change is i'm using the get principal fun instead of the get group, but not sure if that's what has done it. I'm very new to powershell.
    I keep getting an error when adding the user and permission type to roledefinitionbinding. The error is:
    Collection has not been initialized at line 0 char 0.
    The issue is when it runs $collRoleAssign.Add($principal, $collRdb) part and stop with the error above.
    I would really appreciate a hand with this before my PC get launched out of the window.
    Thanks Mark

    Hi,
    The following code snippet for your reference:
    var login = "[email protected]";
    var password = "xxxxxx";
    var siteURL=”https://SharePointOnlineSiteUrl”;
    ClientContext ctx = new ClientContext(siteURL);
    var securePassword = new SecureString();
    foreach (char c in password)
    securePassword.AppendChar(c);
    SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(login, securePassword);
    ctx.Credentials = credentials;
    Web wsite = ctx.Web;
    ctx.Load(wsite, w => w.HasUniqueRoleAssignments, w => w.RoleAssignments.Include(roleAssigned => roleAssigned.Member.Title,
    roleAssigned => roleAssigned.RoleDefinitionBindings.Include(roleDef => roleDef.Name)));
    ctx.ExecuteQuery();
    RoleAssignmentCollection rac = wsite.RoleAssignments;
    if (rac != null && rac.Count !=0)
    Console.WriteLine("Unique Permissions: " + wsite.HasUniqueRoleAssignments);
    foreach (RoleAssignment ra in rac)
    Console.WriteLine("Group Name: " + ra.Member.Title);
    foreach (RoleDefinition rd in ra.RoleDefinitionBindings)
    Console.WriteLine("Permission: " + rd.Name);
    Console.ReadKey();
    More information:
    http://social.technet.microsoft.com/wiki/contents/articles/24087.associate-permission-levels-with-sharepoint-user-groups-using-the-client-side-object-model-in-netc.aspx
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • Iterate Through Lists Instead of Document Libraries, Or both

    System Info: SharePoint 2010 Enterprise w DEC 2013 CU. 2 WFEs (load balanced), App Server, SSRS Server, Dedicated CA Server (All running Win 2k8 R2).
    Background:I have a large (5,000 user) application that is completely customized on top of SP2010. I am the admin, and have been on the team for many years. Previously, we had a development team,
    but client has scaled costs back, and now its just me on the technical side. We have a Web app that houses multiple Site Collections, and each site collection has various subsites.
    My Problem: We have increased the LVT to 10k items (system has plenty of HP, although we do see performance degradation). Each subsite in the Site Collection holds data specific to an organization
    wtihin the Line of Business. There are two lists that frequently approach the 10k mark, and we have mitigation steps in place (essentially, we just create a new SubSite for them once they reach 10k). What I need is a single script that will traverse ALL subsites
    and return a count of their lists, perhaps I can work a couple of if statements in there to have specific data written to a SP List (if count is greater than 5000), and other wise everything gets written to the output file.
    I am trying to iterate through all lists and return a count of folders + items ... The script below works just fine, but it goes through Document Libraries only (per the baseType eq tag).
    I've tried changing baseType from DocumentLibrary to GenericList, but I continually get an error.
    I've also removed the where baseType = DocLib clause completely, and this has the desired results (all lists and doclibs are listed), except the 'WebUrl' field in the csv output is blank.
    Any thoughts on how I can make a small tweak to this script to get my desired results?
    Start-SPAssignment -Global
    $OutputFile ="D:\folder\DocCount3.csv"
    $results = @()
    $webApps = Get-SPWebApplication http://WebAppURL
    foreach($webApp in $webApps)
    foreach($siteColl in $webApp.Sites)
    foreach($web in $siteColl.AllWebs)
    $webUrl = $web.url
    $docLibs = $web.Lists | Where-Object {$_.baseType -eq "DocumentLibrary"}
    $docLibs | Add-Member -MemberType ScriptProperty -Name WebUrl -Value {$webUrl}
    $results += ($docLibs | Select-Object -Property WebUrl, Title, ItemCount)
    $results | Export-Csv -Path $OutputFile -NoTypeInformation
    Stop-SPAssignment –Global

    You guys won't believe this ... But, the script actually works as intended if I change the baseType tag to "GenericList"... I had been getting errors (about 14 of them) through PowerShell and
    assuming the script didn't process, but after looking at the output CSV, it seems that everything worked properly. I think the 14 errors MAY have been corrupted sites (or something?) as it gives me NullValueNotAllowed when trying to "Add-Member" and points
    to $WebUrl as being null.
    Next up -- working on getting this script to write specific objects to a SP list!

  • Any way to get all users's user profile proeprty using CSOM c# for sharepoint online - office 365?

    Any way to get all users's user profile proeprty using CSOM c# for sharepoint online - office 365?

    Since CSOM provides methods for operations related to people per
    user scope, you could retrieve all site users first using SP.Web.siteUsers
    property. and then use SP.UserProfiles.PeopleManager.getUserProfilePropertyFor
    Method to get property.
    [custom.development]

  • Sharepoint online & Sharepoint Designer 2013

    Hi, I am receiving an error each time I try to open a SharePoint online site through SharePoint designer 2013.
    The error is saying "The Server Could not complete your request". I click on 'Details' and get a repeated "403 Forbidden403 Forbidden403 Forbidden" error message. After I pass this message I get a standard "You do not have permission
    to open this web site in SharePoint designer"
    Here are a list of things that have so far not worked for me:
    Using "https://" rather than "http://" - Same issue.
    Removing SharePoint Designer, deleting cache in "users>Roaming>SharePoint designer cache"  - Same issue.
    Clearing Generic Credentials in Credential Manager - Same issue.
    Checking SharePoint site permissions to ensure that " Same issue.
    My Admin role grants no restrictions.
    I have Nintex trials installed and have used it to build forms on the site, I also have Nintex workflow however current tutorials detailing how to do what I need to do require SharePoint Designer 2013.
    Finally SharePoint Developer 2013 has opened sites before, both SharePoint online sites and on prem, but now our company has gone in for the 'real deal' site I can not open this in SharePoint Designer 2013.
    Any support would be very much appreciated, I have been trying to find a solution for a number of days now going into a week.
    Regards,
    Andrew  

    Hi Andrew,
    What permission do you have at site collection level and site level?
    For troubleshooting your issue, please go to your site collection -> site settings -> site collection administration -> SharePoint Designer Settings, make sure you enable the SharePoint Designer.
    Also make sure the o365 sites are added to the trusted sites and the WebClient services (Search: services.msc) is running.Then in SPD go to Account > Switch Account and type in the credentials of the site you are trying to open (it defaults to your
    Microsoft Login).
    Reference:
    http://community.office365.com/en-us/f/154/t/184387.aspx
    https://social.technet.microsoft.com/Forums/en-US/15fd1436-3166-4e43-8b22-cdb480091548/cant-open-sharepoint-online-site-in-sharepoint-designer-2013?forum=sharepointcustomization
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • Can we add users to the 'Manage Access Request' field to process site access request in SharePoint Online?

    Hi,
    I have a requirement in which I have to assign couple of email ids to the "Manage Access Request" field to process site access requests. And, this is possible using server object model but I have to achieve this on SharePoint Online with the help
    of CSOM.
    There are two properties which control the access request configuration, first is "RequestAccessEnabled", a Boolean flag which turns on or off the access request feature for the site. The second property defines one or more email addresses where
    requests will be sent to. It is named "RequestAccessEmail".
    The above both properties are available for server object model but not for CSOM.
    So, is there any other workaround or way to achieve the sane in CSOM?
    Thanks,

    I don't think there is a programmatic workaround for SharePoint Online.  But the email address is just used for Notification.  Anyone with Manage Permissions can approve Access Requests.  If you create an email distribution list for the multiple
    addresses that should be notified you should be able to add the email address for the distribution list into the Access request email field using the user interface.
    Paul Stork SharePoint Server MVP
    Principal Architect: Blue Chip Consulting Group
    Blog: http://dontpapanic.com/blog
    Twitter: Follow @pstork
    Please remember to mark your question as "answered" if this solves your problem.

  • Iterating through all Document Libraries, Folder and Item -Sharepoint 2010

    Hi
    I want to read all RootFolder,Subfolder along with all "items" from Document Librarie.
    Can anyone please advise on this
    Thanks

    Use caml query with recursiveall which
    will fetch all root folder and subfolder data from a document library.
    for
    your reference.
    http://sharepoint.stackexchange.com/questions/29405/get-items-under-folder-caml
    https://social.msdn.microsoft.com/Forums/office/en-US/6beba66a-adcc-4764-ba0d-ba7870d71457/recursive-caml-query?forum=sharepointdevelopmentprevious
    camlQuery.ViewXml = "<View Scope=\"RecursiveAll\"> " +
    "<Query>" +
    "<Where>" +
    "<Eq>" +
    "<FieldRef Name=\"FileDirRef\" />" +
    "<Value Type=\"Text\">/ecm/Business/Business/Projects/IDECO_P01030000</Value>" +
    "</Eq>" +
    "</Where>" +
    "</Query>" +
    "</View>";
    Regards,
    Rajendra Singh
    If a post answers your question, please click Mark As Answer on that post and Vote as Helpful http://sharepointundefind.wordpress.com/
    Regards, Rajendra Singh If a post answers your question, please click Mark As Answer on that ost and Vote as Helpful http://sharepointundefind.wordpress.com/

  • Solution to sign legal documents through SharePoint online

    All:
    I want a solution to get documents signed by 4000 employees in my organization. What I came up with is to create a content type with all three documents and creating folders with name of employees in a document library and use the collect signature workflow.
    But users are new to SharePoint and it will be hard for them to use create new document from the content type and save it and to sign. 
    I came across something called Docusign app which can be used for signing, and in that case we will have to create the folder and add documents to it and then invite them to sign one by one. which is kind of not practical
    I tried to create the document to be signed as a list but the column name field cannot take that much information.
    Same is the problem when I tried to create it as a survey.
    I am looking to create it as a document library/ form library and create a document with instructions on how to open, fill and save the document. So that will be three document libraries for three documents which will save the confusion from content type.
    And no signing as such, we will put a field to put user name in the document and it will be considered as acknowledgment and signature.
    Any other easy ideas on this??
    Thanks in advance!!
    Whenever you see a reply and if you think is helpful, click "Vote As Helpful"! And whenever you see a reply being an answer to the question of the thread, click "Mark As Answer Feel free to unmark answer if does not resolves your problem.

    I have the same problem here.
    The integration works fine outside of Outlook, but if, for example, an account is opened within CRM for Outlook the error occurs.
    - No masterpage modification
    - Some security setting in IE 11 (perhaps IE 11 is the problem)
    - Installed the solution in the used site collection
    - Configured CRM settings
    Dirk

  • Managing Query Suggestions through CSOM (C#) or PowerShell for Sharepoint Online.

    Hello everybody.
    I am currently working with Sharepoint Online search and am trying to find information about managing Query suggestions (CRUD operations).
    Would anybody have any information as to how I could do this in CSOM or PowerShell ? I truely am having a hard time on this.

    Hi,
    Please check below. This should help you. You can REST APIs
    Retrieving query suggestions using the Search REST service
    https://msdn.microsoft.com/en-us/library/office/dn194079.aspx
    Please remember to click 'Mark as Answer' on the answer if it helps you

  • Creating a folder for a document library in SharePoint online

    Hello I am looking for a good place to get started on creating a folder for a document library using a powershell script. Thanks in advance for any help.

    Here is a guide to creating folders and items in a document library for SharePoint Server/Foundation: Creating SharePoint Folders
    and Items with PowerShell. You will need to tailor it to your needs as it's a demo for creating 50,000 items.
    That's step 1 and contains the bulk of what you would need to do. Here's an example of connecting to a library in SharePoint Online using CSOM: Office
    365 - PowerShell Script to Upload Files to a Document Library using CSOM. You won't be uploading files, but the parts where you connect and get a list are what you're interested in.
    Now you'll combine bits from both of these scripts:
    1. Connect to SPO
    2. Get your list (looks like you need to first get the site collection and then the site)
    3. Create a folder
    I figure it would look something like this (note I haven't tested this at all):
    #Specify tenant admin and site URL
    $User = "[email protected]"
    $SiteURL = "https://tenant.sharepoint.com/sites/site"
    $DocLibName = "DocLib"$FolderTitle = "Example Folder"
    #Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
    $Password = Read-Host -Prompt "Please enter your password" -AsSecureString
    #Bind to site collection
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
    $Context.Credentials = $Creds
    #Retrieve list
    $List = $Context.Web.Lists.GetByTitle($DocLibName)
    $folder = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
    $folder["Title"] = $FolderTitle
    $folder.Update();
    Jason Warren
    @jaspnwarren
    jasonwarren.ca
    habaneroconsulting.com/Insights

  • Upload/Download file to/from a document library in a SharePoint online site

    Hi,
    I am referring to the below blog for Upload/Download file to/from a document library in a SharePoint online site.
    http://blogs.msdn.com/b/rohitpuri/archive/2007/04/10/upload-download-file-to-from-wss-document-library-using-dav.aspx?CommentPosted=true#commentmessage
    I would like to know if this is feasible with a SharePoint online site.
    If feasible, how can I resolve the below exception I am getting while using the code.
    “The remote server returned an error: (403) Forbidden”.
    Thanks,
    Thanan

    Hi,
    Actually what I am trying to achieve is the two things.
    1) By using only the user's name, need to upload/download from/to the document library of SharePoint online site using the CSOM. (i.e., achieving Single Sign On / Windows Authentication)
    2) I need to achieve the above only by passing the document URL; not by hardcording/ configuring the document library name in the windows application.
    Can anyone pls help on this now?
    [Below code is working fine. But need to arrive the solution whereas the above 2 conditions are not violated.
    using (var clientContext
    = new ClientContext("https://yoursiteurl.com"))
               string passWd
    = "password";
               SecureString securePassWd
    = new SecureString();
               foreach
    (var c in passWd.ToCharArray())
                    securePassWd.AppendChar(c);
                clientContext.Credentials
    = new SharePointOnlineCredentials("username", securePassWd);
               using
    (var fs =
    new FileStream("fileName",
    FileMode.Open))
    var fi =
    new FileInfo("fileName");
    var list = clientContext.Web.Lists.GetByTitle("Doc Library");
                   clientContext.Load(list.RootFolder);
                   clientContext.ExecuteQuery();
    var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl,
    fi.Name);
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl,
    fs, true);
    Thanks,
    Thanann

  • Count documents in a SharePoint online library using PowerShell

    Hi,
    I would like to use PowerShell to iterate through a site (and its sites) and count how many documents are in each document library.
    Does anyone know if this is possible for SharePoint online please?
    Thanks

    yes. You can set an ID on counter. I don't have any idea about how to do that from the PowerShell but from SharePoint online it is possible by going in to document library settings and then select default view (All documents). Then go and then select
    ID as column and there is an option over there Total. If you select the ID column drop down you will get an option called count select that and click ok. Then go back to your document library and see the count of the documents you have in your doc library.
    If you find this information helpful then please propose this as answer and vote. Thanks.

  • Retriving documents from Sharepoint online by BTS2013 R2

    We are trying to retrieve documents from Sharepoint online by BTS2013 R2  but we are receiving the below error:
    Error:
    The adapter "Windows SharePoint Services" raised an error message. Details "The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for
    communication because it is in the Faulted state.".
    I have crossed checked and user credential is correct. Also the account host instances are running is having access.
    We are facing couple of issues and not sure if we missed an steps to configure.
    If anyone could help us or point through right documentation it would be of great help.

    Hi Rama,
    "The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.".”
     This is quite unhelpful because it does not give a clue of what is going wrong. You get this error because a .NET exception happens on the server side (SharePoint), and nothing catches and handles it. The solution is to check your settings.
    The problem could be with the password of the SharePoint Online Username that is set wrong in the BizTalk adapter.
    Refer:
    BizTalk integration with SharePoint 2013 Online – Troubleshooting
    Also refer:
    SharePoint 2013 and Biztalk 2013 (On-Premise)
    Alternatively, try re-registering the WCF using the below command:
    On x86 environment:
    %Windir%Microsoft.NetFrameworkv3.0Windows Communication FoundationServiceModelReg.exe -r
    On x64 you can re-register WCF using the command:
    %Windir%Microsoft.NetFramework64v3.0Windows Communication FoundationServiceModelReg.exe -r
    Refer:
    VSeWSS 1.3 Deploy fails with "Faulted state"
    Rachit
    Please mark as answer or vote as helpful if my reply does

Maybe you are looking for