User or group column is populated with incorrect values when adding data from CSOM

I am working on a console application that updates list items using managed CSOM. I have a user or group column in this list that can contain multiple values. Now, I am using below code to update the value of this column:

// Get the user   User newUser = web.EnsureUser("LoginName");   context.Load(newUser);   context.ExecuteQuery();   FieldUserValue userValue = new FieldUserValue();   userValue.LookupId = newUser.Id;  // Update the list item   listItem["User"] = userValue; 

The issue is if I assign the value of user1 to this column, the value that I see after the column is updated is another user; like user2. I don’t know why it is populating this code with some other user?

Any idea on this issue?

Project Online CSOM without using SharePointOnlineCredentials

We have a console application running every night which updates some project plans with CSOM. This uses the SharePointOnlineCredentials for authentication.

But the IT departments wants to change the flag of LegacyAuthProtocolsEnabled of the tenant to false. This has as consequence that SharePointOnlineCredentials can no longer be used as you can read here.

A suggested approach in the link above was to use a ClientId and ClientSecret. I’ve tested this with the PnP Core AutheticationManager function GetAppOnlyAuthenticatedContext. This works for a ClientContext object for SharePoint Online but it does not work after modifying this function to return a ProjectContext object. A ProjectServerError “GeneralNotLicensed” is thrown because the SharePoint Principal does not have a Project Online license (see here).

My third attempt was to use the Office365ClaimsHelper class found here. This contacts https://login.microsoftonline.com/extSTS.srf for a SAML token by providing the username and password. Now this approach works for a demo environment, but not for the production environment. I suspect because this has a Multi-Factor authentication.

To put things short: does anyone have an idea on how to get a ProjectContext object without using SharePointOnlineCredentials and without showing a pop-up to log in a user on a Multi-Factor authentication environment?

How to overwrite version of a file using CSOM?

When I check in as a major version or minor version, it creates the new version as a major. Below is the code:

private static void UploadFiles(string sourceFileUrl, Folder targetFolder, string fileName,ClientContext clientContext,ClientContext destinationContext, bool bolMajorVersion)     {          FileCreationInformation targetFileVersionCreationInfo = new FileCreationInformation();         targetFileVersionCreationInfo.Overwrite = true;         try         {             WebRequest request = HttpWebRequest.Create(sourceFileUrl);             request.Credentials = clientContext.Credentials;             using (WebResponse response = request.GetResponse())             {                 using (Stream stream = response.GetResponseStream())                 {                     byte[] verBuffer = new byte[32768];                     using (MemoryStream versionMS = new MemoryStream())                     {                         int read;                         while ((read = stream.Read(verBuffer, 0, verBuffer.Length)) > 0)                         {                             versionMS.Write(verBuffer, 0, read);                         }                         versionMS.Seek(0, SeekOrigin.Begin);                         targetFileVersionCreationInfo.ContentStream = versionMS;                         destinationContext.RequestTimeout = System.Threading.Timeout.Infinite;                         targetFileVersionCreationInfo.Url = targetFolder.ServerRelativeUrl+ "/" + fileName;                         Microsoft.SharePoint.Client.File targetVersionFile = targetFolder.Files.Add(targetFileVersionCreationInfo);                          Microsoft.SharePoint.Client.File file = targetVersionFile;                         //Checkout if checked in                         destinationContext.Load(file);                          destinationContext.ExecuteQuery();                          if (file.CheckOutType == CheckOutType.None)                         {                             file.CheckOut();                         }                         //ListItem lstItem = file.ListItemAllFields;                         //clientContext.Load(lstItem);                         //clientContext.ExecuteQuery();                         if (bolMajorVersion)                         {                              file.CheckIn("Uploaded through portal", CheckinType.MajorCheckIn);                          }                         else                         {                             //Overwrite to avoid creating new version                             file.CheckIn("Uploaded through portal", CheckinType.MinorCheckIn);                         }                         destinationContext.ExecuteQuery();                         //  destinationContext.ExecuteQuery();                          }                 }             }         }         catch (Exception ex)         {             //handle exception         }     } 

The file initially upload with version 0.1 after check in as a major version, it creates new version 1.0 and also keep version 0.1. I need to overwrite this 0.1 version file.

Any help should be appreciated.

Access Old Version File objects with CSOM

I created a WCF service that uses Client-side Object Model (CSOM) to query file information from a SP Document Library.

I need to create a List<File> with all the files associated with all the versions for a given File stored in the Document Library. Is there a way through CSOM to get the File object of old versions of a file?

I found here! a solution for downloading an older version file, but what I need is the File object so I can access the Level property to know if the older version was also approved or not.

I’m doing the following:

List docList = context.Web.Lists.GetByTitle("Documents"); context.Load(docList); context.Load(docList.RootFolder); context.Load(docList.RootFolder.Folders); context.ExecuteQuery();  CamlQuery camlQuery = new CamlQuery(); ListItemCollection docCollection= listaDocs.GetItems(camlQuery); context.Load(docCollection); context.ExecuteQuery();  foreach(var item in docCollection) {      context.Load(item.File);      var versionList = item.File.Versions;      context.Load(versionList);      context.ExecuteQuery();       if(versionList != null)      {           foreach (FileVersion version in versionList)           {               // get version File object somehow               // get version Level property somehow           }      } } 

I know that with Server-side I can access the desired info with:

SPFileVersionCollection versions = file.Versions;  foreach (SPFileVersion version in versions) {     int name = (int)version.File.Level; } 

But because I’m working in an external WCF, I’m using CSOM.

CSOM + SharePoint Online – unable to get list item role assignments

I have made a very simple CSOM program using I have fetched a List Item and I have verified that it has listItem.HasUniqueRoleAssignments = true

So with that being the case, I go ahead attempt to fetch the role assignments using CSOM:

    clientContext.Load(listItem.RoleAssignments,       ras => ras.Include(           item => item.PrincipalId,           item => item.Member.LoginName,           item => item.Member.Title,           item => item.Member.PrincipalType,           item => item.RoleDefinitionBindings));     clientContext.ExecuteQuery(); 

The result of this always returns an empty list.

CSOM WCF XML Request:

<?xml version="1.0" encoding="UTF-8"?> <Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library">    <Actions>       <ObjectPath Id="34" ObjectPathId="33" />       <Query Id="35" ObjectPathId="33">          <Query SelectAllProperties="false">             <Properties />          </Query>          <ChildItemQuery SelectAllProperties="false">             <Properties>                <Property Name="PrincipalId" ScalarProperty="true" />                <Property Name="Member">                   <Query SelectAllProperties="false">                      <Properties>                         <Property Name="LoginName" ScalarProperty="true" />                         <Property Name="Title" ScalarProperty="true" />                         <Property Name="PrincipalType" ScalarProperty="true" />                      </Properties>                   </Query>                </Property>                <Property Name="RoleDefinitionBindings" SelectAll="true">                   <Query SelectAllProperties="false">                      <Properties />                   </Query>                </Property>             </Properties>          </ChildItemQuery>       </Query>    </Actions>    <ObjectPaths>       <Property Id="33" ParentId="27" Name="RoleAssignments" />       <Identity Id="27" Name="6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:list:83780af0-e908-4c51-a1be-49d7e0ac5867:item:2,1" />    </ObjectPaths> </Request> 

CSOM WCF JSON Respons:

[ { "SchemaVersion":"15.0.0.0","LibraryVersion":"16.0.8412.1210","ErrorInfo":null,"TraceCorrelationId":"6b1fb39e-d0c0-7000-b3db-e01045a23af0" },34,{ "IsNull":false },35,{ "_ObjectType_":"SP.RoleAssignmentCollection","_Child_Items_":[  ] } ] 

Here is the list item:

{     "_ObjectType_": "SP.ListItem",     "_ObjectIdentity_": "6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:list:83780af0-e908-4c51-a1be-49d7e0ac5867:item:2,1",     "_ObjectVersion_": "1",     "FileSystemObjectType": 1,     "Id": 2,     "ServerRedirectedEmbedUri": null,     "ServerRedirectedEmbedUrl": "",     "DisplayName": "AB922B82-8406-4E49-B17B-9057BDF09503",     "HasUniqueRoleAssignments": true,     "Folder": {       "_ObjectType_": "SP.Folder",       "_ObjectIdentity_": "6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:folder:6facd266-57e5-4fea-9162-897b9cf2a0fc",       "Exists": true,       "IsWOPIEnabled": false,       "ItemCount": 0,       "Name": "AB922B82-8406-4E49-B17B-9057BDF09503",       "ProgID": null,       "ServerRelativeUrl": "/xxxx/Lists/PublishedFeed/AB922B82-8406-4E49-B17B-9057BDF09503",       "TimeCreated": "/Date(1487190160000)/",       "TimeLastModified": "/Date(1487190160000)/",       "UniqueId": "/Guid(6facd266-57e5-4fea-9162-897b9cf2a0fc)/",       "WelcomePage": ""     },     "File": null,     "ContentType": {       "_ObjectType_": "SP.ContentType",       "_ObjectIdentity_": "6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:list:83780af0-e908-4c51-a1be-49d7e0ac5867:contenttype:0x0120000153FEC126436442892AABB21C3053F4",       "Description": "Create a new folder.",       "DisplayFormTemplateName": "ListForm",       "DisplayFormUrl": "",       "DocumentTemplate": "",       "DocumentTemplateUrl": "",       "EditFormTemplateName": "ListForm",       "EditFormUrl": "",       "Group": "Folder Content Types",       "Hidden": false,       "Id": {         "_ObjectType_": "SP.ContentTypeId",         "StringValue": "0x0120000153FEC126436442892AABB21C3053F4"       },       "JSLink": "",       "MobileDisplayFormUrl": "",       "MobileEditFormUrl": "",       "MobileNewFormUrl": "",       "Name": "Folder",       "NewFormTemplateName": "ListForm",       "NewFormUrl": "",       "ReadOnly": false,       "SchemaXml": "<ContentType ID=\"0x0120000153FEC126436442892AABB21C3053F4\" Name=\"Folder\" Group=\"Folder Content Types\" Description=\"Create a new folder.\" Sealed=\"TRUE\" Version=\"0\" DelayActivateTemplateBinding=\"GROUP,SPSPERS,SITEPAGEPUBLISHING\" FeatureId=\"{695b6570-a48b-4a8e-8ea5-26ea7fc1d162}\"><Fields><Field ID=\"{c042a256-787d-4a6f-8a8a-cf6ab767f12d}\" Type=\"Computed\" DisplayName=\"Content Type\" Name=\"ContentType\" DisplaceOnUpgrade=\"TRUE\" RenderXMLUsingPattern=\"TRUE\" Sortable=\"FALSE\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"ContentType\" Group=\"_Hidden\" PITarget=\"MicrosoftWindowsSharePointServices\" PIAttribute=\"ContentTypeID\" FromBaseType=\"TRUE\"><FieldRefs><FieldRef Name=\"ContentTypeId\"/></FieldRefs><DisplayPattern><MapToContentType><Column Name=\"ContentTypeId\"/></MapToContentType></DisplayPattern></Field><Field ID=\"{fa564e0f-0c70-4ab9-b863-0177e6ddd247}\" Type=\"Text\" Name=\"Title\" DisplayName=\"Title\" Required=\"FALSE\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"Title\" FromBaseType=\"TRUE\" ColName=\"nvarchar1\" Hidden=\"TRUE\"/><Field ID=\"{8553196d-ec8d-4564-9861-3dbe931050c8}\" Hidden=\"FALSE\" ShowInFileDlg=\"FALSE\" ShowInVersionHistory=\"FALSE\" Type=\"File\" Name=\"FileLeafRef\" DisplaceOnUpgrade=\"TRUE\" DisplayName=\"Name\" AuthoringInfo=\"(for use in forms)\" List=\"Docs\" FieldRef=\"ID\" ShowField=\"LeafName\" JoinColName=\"DoclibRowId\" JoinRowOrdinal=\"0\" JoinType=\"INNER\" NoCustomize=\"TRUE\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"FileLeafRef\" FromBaseType=\"TRUE\" Required=\"TRUE\"/><Field ID=\"{b824e17e-a1b3-426e-aecf-f0184d900485}\" Name=\"ItemChildCount\" DisplaceOnUpgrade=\"TRUE\" ReadOnly=\"TRUE\" ShowInFileDlg=\"FALSE\" Type=\"Lookup\" DisplayName=\"Item Child Count\" List=\"Docs\" FieldRef=\"ID\" ShowField=\"ItemChildCount\" JoinColName=\"DoclibRowId\" JoinRowOrdinal=\"0\" JoinType=\"INNER\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"ItemChildCount\" FromBaseType=\"TRUE\"/><Field ID=\"{960ff01f-2b6d-4f1b-9c3f-e19ad8927341}\" Name=\"FolderChildCount\" DisplaceOnUpgrade=\"TRUE\" ReadOnly=\"TRUE\" ShowInFileDlg=\"FALSE\" Type=\"Lookup\" DisplayName=\"Folder Child Count\" List=\"Docs\" FieldRef=\"ID\" ShowField=\"FolderChildCount\" JoinColName=\"DoclibRowId\" JoinRowOrdinal=\"0\" JoinType=\"INNER\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"FolderChildCount\" FromBaseType=\"TRUE\"/></Fields><XmlDocuments><XmlDocument NamespaceURI=\"http://schemas.microsoft.com/sharepoint/v3/contenttype/forms\"><FormTemplates xmlns=\"http://schemas.microsoft.com/sharepoint/v3/contenttype/forms\"><Display>ListForm</Display><Edit>ListForm</Edit><New>ListForm</New></FormTemplates></XmlDocument></XmlDocuments></ContentType>",       "Scope": "/xxxx/Lists/PublishedFeed",       "Sealed": true,       "StringId": "0x0120000153FEC126436442892AABB21C3053F4"     },     "ContentTypeId": {       "_ObjectType_": "SP.ContentTypeId",       "StringValue": "0x0120000153FEC126436442892AABB21C3053F4"     },     "Title": "AB922B82-8406-4E49-B17B-9057BDF09503",     "_ModerationComments": null,     "File_x0020_Type": null,     "MicroBlogType": null,     "PostAuthor": null,     "DefinitionId": null,     "RootPostID": null,     "RootPostOwnerID": null,     "RootPostUniqueID": null,     "ReplyCount": null,     "ReferenceID": null,     "Attributes": null,     "Content": null,     "ContentData": null,     "SearchContent": null,     "RefRoot": null,     "RefReply": null,     "PostSource": null,     "PeopleCount": null,     "PeopleList": null,     "MediaLinkType": null,     "MediaLinkDescription": null,     "PostSourceUri": null,     "MediaLinkURI": null,     "MediaLinkUISnippet": null,     "MediaLinkContentURI": null,     "MediaLength": null,     "MediaWidth": null,     "MediaHeight": null,     "MediaPreviewWidth": null,     "MediaPreviewHeight": null,     "MediaActionWidth": null,     "MediaActionHeight": null,     "MediaActionClickUrl": null,     "MediaActionClickKind": null,     "eMailSubscribers": null,     "eMailUnsubscribed": null,     "RemoteLocation": null,     "LikesCount": null,     "LikedBy": null,     "HashTags": {       "_ObjectType_": "SP.Taxonomy.TaxonomyFieldValueCollection",       "_Child_Items_": []     },     "j33b1bc20532487296f1bbbdead35a56": null,     "TaxCatchAll$  SP.FieldLookupValue$    Array": [],     "TaxCatchAllLabel$  SP.FieldLookupValue$    Array": [],     "ComplianceAssetId": null,     "ID$    Int32": 2,     "Modified": "/Date(1487190160000)/",     "Created": "/Date(1487190160000)/",     "Author": {       "_ObjectType_": "SP.FieldUserValue",       "LookupId": 12,       "LookupValue": "xxxxxxxxx",       "Email": "xxxxxxxxx@xxxxxxxxxx.onmicrosoft.com"     },     "Editor": {       "_ObjectType_": "SP.FieldUserValue",       "LookupId": 12,       "LookupValue": "xxxxxxxxx",       "Email": "xxxxxxxxx@xxxxxxxxxx.onmicrosoft.com"     },     "_HasCopyDestinations": null,     "_CopySource": null,     "owshiddenversion$    Int32": 1,     "WorkflowVersion$    Int32": 1,     "_UIVersion$    Int32": 512,     "_UIVersionString": "1.0",     "Attachments": false,     "_ModerationStatus$    Int32": 0,     "InstanceID": null,     "Order$   Double": 200,     "GUID": "/Guid(e52decf3-c64b-4cd5-bad2-e1a40c812dae)/",     "WorkflowInstanceID": null,     "FileRef": "/xxxx/Lists/PublishedFeed/AB922B82-8406-4E49-B17B-9057BDF09503",     "FileDirRef": "/xxxx/Lists/PublishedFeed",     "Last_x0020_Modified": "2017-02-15T20:22:40Z",     "Created_x0020_Date": "2017-02-15T20:22:40Z",     "FSObjType": "1",     "SortBehavior": {       "_ObjectType_": "SP.FieldLookupValue",       "LookupId": 2,       "LookupValue": "1"     },     "FileLeafRef": "AB922B82-8406-4E49-B17B-9057BDF09503",     "UniqueId": "/Guid(6facd266-57e5-4fea-9162-897b9cf2a0fc)/",     "SyncClientId": {       "_ObjectType_": "SP.FieldLookupValue",       "LookupId": 2,       "LookupValue": null     },     "ProgId": "",     "ScopeId": "{19A9D84C-A79A-40DC-9E4D-2FE84DAB81E0}",     "MetaInfo": "",     "_Level$    Int32": 1,     "_IsCurrentVersion": true,     "ItemChildCount": "0",     "FolderChildCount": "0",     "Restricted": "",     "OriginatorId": "",     "NoExecute": "0",     "ContentVersion": "0",     "_ComplianceFlags": "",     "_ComplianceTag": "",     "_ComplianceTagWrittenTime": "",     "_ComplianceTagUserId": "",     "AccessPolicy": "",     "_VirusStatus": "",     "_VirusVendorID": "",     "_VirusInfo": "",     "AppAuthor": null,     "AppEditor": null,     "SMTotalSize": {       "_ObjectType_": "SP.FieldLookupValue",       "LookupId": 244,       "LookupValue": ""     },     "SMLastModifiedDate": "2017-02-15T20:22:40Z",     "SMTotalFileStreamSize": "0",     "SMTotalFileCount": {       "_ObjectType_": "SP.FieldLookupValue",       "LookupId": 0,       "LookupValue": ""     }   } 

Why can’t I fetch the Role assignments for the list item with C# CSOM code in SharePoint Online?

CSOM CAML displays all fields

I would like to reduce the no of fields that I get from CAML query. The List has more than 100 fields, which is causing a lot of performance issues.

In SSOM the SPQuery object has a query.ViewFieldsOnly = true;. Currently I am querying SharePoint online using CSOM i.e. using c#. I do not get the ViewFieldsonly property.

Following is the code I use to get the ListItem

ClientContext context = new ClientContext("http://SiteUrl"); ListCollection lcoll = context.Web.Lists; context.Load(lcoll); context.ExecuteQuery(); lst = lcoll.Where(x => x.Title == ListName).FirstOrDefault(); CamlQuery cQuery = new CamlQuery(); cQuery.ViewXml ="<View>"+                   "<Query>"+                     "<Where><Eq>"+                      "<FieldRef Name='MyName'/>"                      "<Value Type='Text'>John"+                      "Ranger</Value>"+                     "</Eq></Where>"+                    "</Query>"+                  "<ViewFields>"+                  "<FieldRef Name='MyName'/>"+                  "<FieldRef Name='Title' />"+                  "<FieldRef Name='ID' />"+                "</ViewFields></View>"; ListItemCollection licoll = lst .GetItems(cQuery); context.Load(licoll); context.ExecuteQuery(); ListItem item = licoll.Where(i => i[MyName].ToString()== email).FirstOrDefault(); context.Load(item); context.ExecuteQuery(); 

Using the CAML query gives me one list item but with 179 fields. I only want the three fields that I have specified in the CAML query.

Optimize CSOM Query To SharePoint

I am using C# CSOM to query SharePoint and return data. It takes anywhere between 30 seconds and 60 seconds to return the data, and I was curious if there was any optimization that could be done to make this return the data quicker.

Below is my syntax:

private void GetClients()        {           string conNum = null;           string accName = null;           string sysName = null;             //Querying SharePoint to return the data            using(var ctx = new ClientContext(StartPage.D3PURL))            {                    var web = ctx.Web;               Microsoft.SharePoint.Client.List list = web.Lists.GetByTitle(StartPage.D3PSite);               CamlQuery caml = new CamlQuery();               caml.ViewXml = "<View><ViewFields><FieldRef Name=‘Acc_Name’/><FieldRef Name=‘Con_Name’ /><FieldRef Name=‘Sys_Name’ /></ViewFields><Query><OrderBy><FieldRef Name=‘Acc_Name’ Ascending='TRUE' /></OrderBy></Query></View>";               ListItemCollection items = list.GetItems(caml);               ctx.Load(items);               ctx.ExecuteQuery();                 //Create DataTable To Store Results In                    dtData = new System.Data.DataTable();               DataRow newRow = dtData.NewRow();               dtData.Columns.Add("accName", typeof(string));               dtData.Columns.Add("conNum", typeof(string));                               dtData.Columns.Add("sysName", typeof(string));                foreach(ListItem li in items)                {                   newRow = dtData.NewRow();                    FieldLookupValue an = li[“Acc_Name”] as FieldLookupValue;                   accName = an.LookupValue;                   newRow["accName"] = accName;                   clients.Add(accName);                    string helpsysName = null;                            var sysname = li[“Sys_Name”] as FieldLookupValue[];                            if (sysname != null)                    {                       foreach(var system in sysname)                        {                           sysName = system.LookupValue;                           helpsysName += sysName + "; ";                                    }                       newRow["sysName"] = helpsysName;                            }                    string helpAccNum = null;                            var cntnum = li[“Con_Name”] as FieldLookupValue[];                            if (cntnum != null)                    {                       foreach(var contracts in cntnum)                        {                           conNum = contracts.LookupValue;                           helpAccNum += conNum + "; ";                                    }                       newRow["conNum"] = helpAccNum;                            }                   dtData.Rows.Add(newRow);                    }            }        

}

CSOM Powershell create subsite in subsite

Trying to create multiple things in PowerShell with CSOM for SharePoint Online:

  1. Create a project (subsite) in the site collection (root)
  2. Create a level (subsite) underneath the project subsite (so basically a subsite under an existing subsite).

I used this code to create a subsite in the root:

#Specify tenant admin and site URL $  Username = "admin@contoso.onmicrosoft.com" $  Password = Read-Host -Prompt "Please enter your password" -AsSecureString $  Site = "https://contoso.sharepoint.com/sites/projects" $  Context = New-Object Microsoft.SharePoint.Client.ClientContext($  Site) $  Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($  Username,$  Password) $  Context.Credentials = $  Creds  #Search Subsite Templates #$  Templates = $  Context.Site.GetWebTemplates("1043","0") #$  Context.Load($  Templates) #$  Context.ExecuteQuery() #$  Templates | Where {$  _.Name -like "*STS#0*" } | Select Name, Description  #Main / project  #Load CSV $  dataSource = import-csv “C:\temp\contoso.csv”  foreach($  dataRecord in $  dataSource) {      #Define properties $  projectnummer = $  dataRecord.Projectnummer $  project = $  dataRecord.Project  #check if subsite is present or not $  web = $  Context.Web  $  Context.Load($  web.Webs)    $  Context.ExecuteQuery()  $  subweb = $  web.Webs | where{$  _.Url -like "*$  projectnummer*"} if($  subweb) {     #Execute if subsite exists     Write-Host "Project $  projectnummer exists" -ForegroundColor Green     continue } else {     #Execute if subsite does not exists     Write-Host "Project $  projectnummer does not exists yet, creating..." -ForegroundColor Green      #Create Subsite in root     $  Subsite = New-Object Microsoft.SharePoint.Client.WebCreationInformation     $  Subsite.WebTemplate = "STS#0"     $  Subsite.Title = "$  project"     $  Subsite.Description = "$  projectnummer"     $  Subsite.Url = $  projectnummer     $  Subsite.Language = "1043"     $  SubWeb = $  Context.Web.Webs.Add($  Subsite)     $  Context.Load($  SubWeb)     $  Context.ExecuteQuery() } } 

This is working, but now I want to create a subsite in the subsite that is just created, but how? I changed the $ site value with this, but that did not work: $ Site = $ Site + "/" + $ projectnummer + "/"

In that subsite, I also need to create multiple document libraries, but I think I can do that as long as I can create the correct subsite at the right location.