/// <summary> /// Ensures the folder to which the file is to be uploaded exists. Changed from using the EnsureFolder implementation in PnP Framework as that requires at least member rights to the entire site to work. /// </summary> /// <returns>The folder to which the file needs to be uploaded</returns> private Folder EnsureFolder() { // First try to get the folder if it exists already. This avoids an Access Denied exception if the current user doesn't have Full Control access at Web level CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); Folder folder = null; try { folder = Folder.GetFolder(CurrentWeb); folder.EnsureProperties(f => f.ServerRelativeUrl); return(folder); } // Exception will be thrown if the folder does not exist yet on SharePoint catch (ServerException serverEx) when(serverEx.ServerErrorCode == -2147024894) { // Try to create the folder folder = CurrentWeb.EnsureFolder(CurrentWeb.RootFolder, Folder.ServerRelativeUrl); folder.EnsureProperties(f => f.ServerRelativeUrl); return(folder); } }
protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Batch))) { var list = List.GetList(Batch); list.EnsureProperties(l => l.Id, l => l.Fields.LoadProperties(f => f.Id, f => f.Title, f => f.InternalName, f => f.TypeAsString)); var values = ListItemHelper.GetFieldValues(list, null, Values, ClientContext); if (ContentType != null) { var contentType = ContentType.GetContentType(Batch, list); values.Add("ContentTypeId", contentType.StringId); } list.Items.AddBatch(Batch.Batch, values, Folder); } else { List list = List.GetList(CurrentWeb); ListItemCreationInformation liCI = new ListItemCreationInformation(); if (Folder != null) { // Create the folder if it doesn't exist var rootFolder = list.EnsureProperty(l => l.RootFolder); var targetFolder = CurrentWeb.EnsureFolder(rootFolder, Folder); liCI.FolderUrl = targetFolder.ServerRelativeUrl; } var item = list.AddItem(liCI); bool systemUpdate = false; if (ContentType != null) { var ct = ContentType.GetContentType(list); if (ct != null) { item["ContentTypeId"] = ct.EnsureProperty(w => w.StringId); item.Update(); systemUpdate = true; ClientContext.ExecuteQueryRetry(); } } if (Values?.Count > 0) { ListItemHelper.SetFieldValues(item, Values, this); } if (!String.IsNullOrEmpty(Label)) { IList <Microsoft.SharePoint.Client.CompliancePolicy.ComplianceTag> tags = Microsoft.SharePoint.Client.CompliancePolicy.SPPolicyStoreProxy.GetAvailableTagsForSite(ClientContext, ClientContext.Url); ClientContext.ExecuteQueryRetry(); var tag = tags.Where(t => t.TagName == Label).FirstOrDefault(); if (tag != null) { item.SetComplianceTag(tag.TagName, tag.BlockDelete, tag.BlockEdit, tag.IsEventTag, tag.SuperLock); } else { WriteWarning("Can not find compliance tag with value: " + Label); } } if (systemUpdate) { item.SystemUpdate(); } else { item.Update(); } ClientContext.Load(item); ClientContext.ExecuteQueryRetry(); WriteObject(item); } }