protected override void ExecuteCmdlet() { var serverRelativeWebUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant())) { ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl); } var properties = CurrentWeb.GetWebPartProperties(Identity, ServerRelativePageUrl); var values = properties.FieldValues.Select(x => new PropertyBagValue() { Key = x.Key, Value = x.Value }); if (!string.IsNullOrEmpty(Key)) { var value = values.FirstOrDefault(v => v.Key == Key); if (value != null) { WriteObject(value.Value); } } else { WriteObject(values, true); } }
protected override void ExecuteCmdlet() { if (string.IsNullOrEmpty(Folder)) { if (CurrentWeb.PropertyBagContainsKey(Key)) { if (Force || ShouldContinue(string.Format(Properties.Resources.Delete0, Key), Properties.Resources.Confirm)) { CurrentWeb.RemovePropertyBagValue(Key); } } } else { CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); var folderUrl = UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, Folder); var folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl)); folder.EnsureProperty(f => f.Properties); if (folder.Properties.FieldValues.ContainsKey(Key)) { if (Force || ShouldContinue(string.Format(Properties.Resources.Delete0, Key), Properties.Resources.Confirm)) { folder.Properties[Key] = null; folder.Properties.FieldValues.Remove(Key); folder.Update(); ClientContext.ExecuteQueryRetry(); } } } }
protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterSet_SITE) { var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); ServerRelativeUrl = UrlUtility.Combine(webUrl, SiteRelativeUrl); } var file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(ServerRelativeUrl)); ClientContext.Load(file, f => f.Name); ClientContext.ExecuteQueryRetry(); if (Force || ShouldContinue(string.Format(Resources.Delete0, file.Name), Resources.Confirm)) { if (Recycle) { file.Recycle(); } else { file.DeleteObject(); } ClientContext.ExecuteQueryRetry(); } }
protected override void ExecuteCmdlet() { var serverRelativeWebUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant())) { ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl); } if (Value.BaseObject is string) { CurrentWeb.SetWebPartProperty(Key, Value.ToString(), Identity, ServerRelativePageUrl); } else if (Value.BaseObject is int) { CurrentWeb.SetWebPartProperty(Key, (int)Value.BaseObject, Identity, ServerRelativePageUrl); } else if (Value.BaseObject is bool) { CurrentWeb.SetWebPartProperty(Key, (bool)Value.BaseObject, Identity, ServerRelativePageUrl); } else { ThrowTerminatingError(new ErrorRecord(new Exception("Type of value is not supported. Has to be of type string, int or bool"), "UNSUPPORTEDTYPE", ErrorCategory.InvalidType, this)); } }
protected override void ExecuteCmdlet() { var url = CurrentWeb.EnsureProperty(w => w.Url); var tenantUrl = UrlUtilities.GetTenantAdministrationUrl(ClientContext.Url); using (var tenantContext = ClientContext.Clone(tenantUrl)) { var tenant = new Tenant(tenantContext); var webUrl = url; if (!string.IsNullOrEmpty(WebUrl)) { try { var uri = new Uri(WebUrl); webUrl = WebUrl; } catch { ThrowTerminatingError(new ErrorRecord(new System.Exception("Invalid URL"), "INVALIDURL", ErrorCategory.InvalidArgument, WebUrl)); } } tenant.SetWebTheme(Theme.Name, webUrl); tenantContext.ExecuteQueryRetry(); } }
protected override void ExecuteCmdlet() { var url = CurrentWeb.EnsureProperty(w => w.Url); var tenantUrl = UrlUtilities.GetTenantAdministrationUrl(ClientContext.Url); using (var tenantContext = ClientContext.Clone(tenantUrl)) { var tenant = new Tenant(tenantContext); var webUrl = url; if (!string.IsNullOrEmpty(WebUrl)) { try { var uri = new System.Uri(WebUrl); webUrl = WebUrl; } catch { ThrowTerminatingError(new ErrorRecord(new System.Exception("Invalid URL"), "INVALIDURL", ErrorCategory.InvalidArgument, WebUrl)); } } TenantSiteDesign design = Identity.GetTenantSiteDesign(tenant); if (design != null) { var results = tenant.ApplySiteDesign(webUrl, design.Id); tenantContext.Load(results); tenantContext.ExecuteQueryRetry(); WriteObject(results, true); } } }
protected override void ExecuteCmdlet() { var serverRelativeUrl = string.Empty; var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!Url.ToLower().StartsWith(webUrl.ToLower())) { serverRelativeUrl = UrlUtility.Combine(webUrl, Url); } else { serverRelativeUrl = Url; } File file; file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); ClientContext.Load(file, f => f.Exists, f => f.Versions.IncludeWithDefaultProperties(i => i.CreatedBy)); ClientContext.ExecuteQueryRetry(); if (file.Exists) { var versions = file.Versions; ClientContext.ExecuteQueryRetry(); WriteObject(versions); } }
protected override void ExecuteCmdlet() { var serverRelativeWebUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant())) { ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl); } if (ParameterSetName == "NAME") { CurrentWeb.DeleteWebPart(ServerRelativePageUrl, Title); } else { var wps = CurrentWeb.GetWebParts(ServerRelativePageUrl); var wp = from w in wps where w.Id == Identity select w; var webPartDefinitions = wp as WebPartDefinition[] ?? wp.ToArray(); if (webPartDefinitions.Any()) { webPartDefinitions.FirstOrDefault().DeleteWebPart(); ClientContext.ExecuteQueryRetry(); } } }
protected override void ExecuteCmdlet() { var serverRelativeWebUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant())) { ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl); } Guid id; if (Identity.Id == Guid.Empty) { var wp = CurrentWeb.GetWebParts(ServerRelativePageUrl).FirstOrDefault(wps => wps.WebPart.Title == Identity.Title); if (wp != null) { id = wp.Id; } else { throw new Exception($"Web Part with title '{Identity.Title}' cannot be found on page with URL {ServerRelativePageUrl}"); } } else { id = Identity.Id; } WriteObject(CurrentWeb.GetWebPartXml(id, ServerRelativePageUrl)); }
protected override void ExecuteCmdlet() { var rootWebServerRelativeUrl = (CurrentWeb.Context as ClientContext).Site.RootWeb.EnsureProperty(r => r.ServerRelativeUrl); var serverRelativeUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (ColorPaletteUrl == null) { ColorPaletteUrl = "/_catalogs/theme/15/palette001.spcolor"; } if (!ColorPaletteUrl.ToLower().StartsWith(rootWebServerRelativeUrl.ToLower())) { ColorPaletteUrl = UrlUtility.Combine(rootWebServerRelativeUrl, ColorPaletteUrl); } if (!string.IsNullOrEmpty(FontSchemeUrl) && !FontSchemeUrl.ToLower().StartsWith(rootWebServerRelativeUrl.ToLower())) { FontSchemeUrl = UrlUtility.Combine(rootWebServerRelativeUrl, FontSchemeUrl); } if (!string.IsNullOrEmpty(BackgroundImageUrl) && BackgroundImageUrl.ToLower().StartsWith(rootWebServerRelativeUrl.ToLower())) { BackgroundImageUrl = UrlUtility.Combine(rootWebServerRelativeUrl, BackgroundImageUrl); } CurrentWeb.SetThemeByUrl(ColorPaletteUrl, FontSchemeUrl, BackgroundImageUrl, ResetSubwebsToInherit, UpdateRootWebOnly); ClientContext.ExecuteQueryRetry(); if (!CurrentWeb.IsNoScriptSite()) { ComposedLook composedLook; // Set the corresponding property bag value which is used by the provisioning engine if (CurrentWeb.PropertyBagContainsKey(PROPBAGKEY)) { composedLook = JsonSerializer.Deserialize <ComposedLook>(CurrentWeb.GetPropertyBagValueString(PROPBAGKEY, "")); } else { composedLook = new ComposedLook { BackgroundFile = "" }; CurrentWeb.EnsureProperty(w => w.AlternateCssUrl); composedLook.ColorFile = ""; CurrentWeb.EnsureProperty(w => w.MasterUrl); composedLook.FontFile = ""; CurrentWeb.EnsureProperty(w => w.SiteLogoUrl); } composedLook.Name = composedLook.Name ?? "Custom by PnP PowerShell"; composedLook.ColorFile = ColorPaletteUrl ?? composedLook.ColorFile; composedLook.FontFile = FontSchemeUrl ?? composedLook.FontFile; composedLook.BackgroundFile = BackgroundImageUrl ?? composedLook.BackgroundFile; var composedLookJson = JsonSerializer.Serialize(composedLook); CurrentWeb.SetPropertyBagValue(PROPBAGKEY, composedLookJson); } }
protected override void ExecuteCmdlet() { var webServerRelativeUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!SourceUrl.StartsWith("/")) { SourceUrl = UrlUtility.Combine(webServerRelativeUrl, SourceUrl); } if (!TargetUrl.StartsWith("/")) { TargetUrl = UrlUtility.Combine(webServerRelativeUrl, TargetUrl); } string sourceFolder = SourceUrl.Substring(0, SourceUrl.LastIndexOf('/')); string targetFolder = TargetUrl; if (System.IO.Path.HasExtension(TargetUrl)) { targetFolder = TargetUrl.Substring(0, TargetUrl.LastIndexOf('/')); } Uri currentContextUri = new Uri(ClientContext.Url); Uri sourceUri = new Uri(currentContextUri, EncodePath(sourceFolder)); Uri sourceWebUri = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, sourceUri); Uri targetUri = new Uri(currentContextUri, EncodePath(targetFolder)); Uri targetWebUri = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, targetUri); if (Force || ShouldContinue(string.Format(Resources.MoveFile0To1, SourceUrl, TargetUrl), Resources.Confirm)) { if (sourceWebUri != targetWebUri) { Move(currentContextUri, sourceUri, targetUri, SourceUrl, TargetUrl, false); } else { var isFolder = false; try { var folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(TargetUrl)); var folderServerRelativePath = folder.EnsureProperty(f => f.ServerRelativePath); isFolder = folderServerRelativePath.DecodedUrl == ResourcePath.FromDecodedUrl(TargetUrl).DecodedUrl; } catch { } if (isFolder) { Move(currentContextUri, sourceUri, targetUri, SourceUrl, TargetUrl, true); } else { var file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl)); file.MoveToUsingPath(ResourcePath.FromDecodedUrl(TargetUrl), Overwrite ? MoveOperations.Overwrite : MoveOperations.None); ClientContext.ExecuteQueryRetry(); } } } }
protected override void ExecuteCmdlet() { CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); Folder folder = Folder.GetFolder(CurrentWeb); var result = folder.CreateFolder(Name); WriteObject(result); }
protected override void ExecuteCmdlet() { try { if (!ParameterSpecified(nameof(Folder))) { if (!Indexed) { // If it is already an indexed property we still have to add it back to the indexed properties Indexed = !string.IsNullOrEmpty(CurrentWeb.GetIndexedPropertyBagKeys().FirstOrDefault(k => k == Key)); } CurrentWeb.SetPropertyBagValue(Key, Value); if (Indexed) { CurrentWeb.AddIndexedPropertyBagKey(Key); } else { CurrentWeb.RemoveIndexedPropertyBagKey(Key); } } else { CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); var folderUrl = UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, Folder); var folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl)); folder.EnsureProperty(f => f.Properties); folder.Properties[Key] = Value; folder.Update(); ClientContext.ExecuteQueryRetry(); } } catch (Exception ex) { if (ex is ServerUnauthorizedAccessException) { if (CurrentWeb.IsNoScriptSite()) { ThrowTerminatingError(new ErrorRecord(new Exception($"{ex.Message} Site might have NoScript enabled, this prevents setting some property bag values.", ex), "NoScriptEnabled", ErrorCategory.InvalidOperation, this)); return; } throw; } else { throw; } } }
protected override void ExecuteCmdlet() { if (ParameterSetName == "SITE") { var serverUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); ServerRelativePageUrl = UrlUtility.Combine(serverUrl, SiteRelativePageUrl); } var file = CurrentWeb.GetFileByServerRelativeUrl(ServerRelativePageUrl); file.DeleteObject(); ClientContext.ExecuteQueryRetry(); }
protected override void ExecuteCmdlet() { var serverRelativeUrl = string.Empty; var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!Url.ToLower().StartsWith(webUrl.ToLower())) { serverRelativeUrl = UrlUtility.Combine(webUrl, Url); } else { serverRelativeUrl = Url; } File file; file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); ClientContext.Load(file, f => f.Exists, f => f.Versions.IncludeWithDefaultProperties(i => i.CreatedBy)); ClientContext.ExecuteQueryRetry(); if (file.Exists) { var versions = file.Versions; if (Force || ShouldContinue("Restoring a previous version will overwrite the current version.", Resources.Confirm)) { if (!string.IsNullOrEmpty(Identity.Label)) { versions.RestoreByLabel(Identity.Label); ClientContext.ExecuteQueryRetry(); WriteObject("Version restored"); } else if (Identity.Id != -1) { var version = versions.GetById(Identity.Id); ClientContext.Load(version); ClientContext.ExecuteQueryRetry(); versions.RestoreByLabel(version.VersionLabel); ClientContext.ExecuteQueryRetry(); WriteObject("Version restored"); } } } else { throw new PSArgumentException("File not found", nameof(Url)); } }
protected override void ExecuteCmdlet() { CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); var sourceFolderUrl = UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, Folder); Folder sourceFolder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(sourceFolderUrl)); ClientContext.Load(sourceFolder, f => f.Name, f => f.ServerRelativePath); ClientContext.ExecuteQueryRetry(); var targetPath = string.Concat(sourceFolder.ServerRelativePath.DecodedUrl.Remove(sourceFolder.ServerRelativePath.DecodedUrl.Length - sourceFolder.Name.Length), TargetFolderName); sourceFolder.MoveToUsingPath(ResourcePath.FromDecodedUrl(targetPath)); ClientContext.ExecuteQueryRetry(); }
protected override void ExecuteCmdlet() { if (string.IsNullOrEmpty(Folder)) { if (!string.IsNullOrEmpty(Key)) { WriteObject(CurrentWeb.GetPropertyBagValueString(Key, string.Empty)); } else { CurrentWeb.EnsureProperty(w => w.AllProperties); var values = CurrentWeb.AllProperties.FieldValues.Select(x => new PropertyBagValue() { Key = x.Key, Value = x.Value }); WriteObject(values, true); } } else { // Folder Property Bag CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); var folderUrl = UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, Folder); var folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl)); folder.EnsureProperty(f => f.Properties); if (!string.IsNullOrEmpty(Key)) { var value = folder.Properties.FieldValues.FirstOrDefault(x => x.Key == Key); WriteObject(value.Value, true); } else { var values = folder.Properties.FieldValues.Select(x => new PropertyBagValue() { Key = x.Key, Value = x.Value }); WriteObject(values, true); } } }
protected override void ExecuteCmdlet() { var serverRelativeWebUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant())) { ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl); } WebPartEntity wp = null; switch (ParameterSetName) { case "FILE": if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (File.Exists(Path)) { var fileStream = new StreamReader(Path); var webPartString = fileStream.ReadToEnd(); fileStream.Close(); wp = new WebPartEntity { WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = webPartString }; } break; case "XML": wp = new WebPartEntity { WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = Xml }; break; } if (wp != null) { CurrentWeb.AddWebPartToWebPartPage(ServerRelativePageUrl, wp); } }
protected override void ExecuteCmdlet() { DefaultRetrievalExpressions = new Expression <Func <Folder, object> >[] { f => f.ServerRelativeUrl, f => f.Name, f => f.TimeLastModified, f => f.ItemCount }; if (List != null) { // Gets the provided list var list = List.GetList(CurrentWeb); // Query for all folders in the list CamlQuery query = CamlQuery.CreateAllFoldersQuery(); do { // Execute the query. It will retrieve all properties of the folders. Refraining to using the RetrievalExpressions would cause a tremendous increased load on SharePoint as it would have to execute a query per list item which would be less efficient, especially on lists with many folders, than just getting all properties directly ListItemCollection listItems = list.GetItems(query); ClientContext.Load(listItems, item => item.Include(t => t.Folder), item => item.ListItemCollectionPosition); ClientContext.ExecuteQueryRetry(); // Take all the folders from the resulting list items and put them in a list to return var folders = new List <Folder>(listItems.Count); foreach (ListItem listItem in listItems) { var folder = listItem.Folder; folders.Add(folder); } WriteObject(folders, true); query.ListItemCollectionPosition = listItems.ListItemCollectionPosition; } while (query.ListItemCollectionPosition != null); } else { var webServerRelativeUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!Url.StartsWith(webServerRelativeUrl, StringComparison.OrdinalIgnoreCase)) { Url = UrlUtility.Combine(webServerRelativeUrl, Url); } var folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(Url)); folder.EnsureProperties(RetrievalExpressions); WriteObject(folder); } }
protected override void ExecuteCmdlet() { var url = CurrentWeb.EnsureProperty(w => w.Url); var tenantUrl = UrlUtilities.GetTenantAdministrationUrl(ClientContext.Url); using (var tenantContext = ClientContext.Clone(tenantUrl)) { var webUrl = url; if (!string.IsNullOrEmpty(WebUrl)) { try { var uri = new System.Uri(WebUrl); webUrl = WebUrl; } catch { ThrowTerminatingError(new ErrorRecord(new System.Exception("Invalid URL"), "INVALIDURL", ErrorCategory.InvalidArgument, WebUrl)); } } try { var designTask = Tenant.AddSiteDesignTask(tenantContext, webUrl, SiteDesignId); tenantContext.Load(designTask); tenantContext.ExecuteQueryRetry(); WriteObject(designTask); } catch (System.Net.WebException ex) { if (ex.Status == System.Net.WebExceptionStatus.ProtocolError) { var webResponse = ex.Response as System.Net.HttpWebResponse; if (null != webResponse && webResponse.StatusCode == System.Net.HttpStatusCode.Forbidden) { WriteObject("The server threw an exception (see below). It seems you may not have access to the server or you are executing this script outside of the tenant admin URL eg. yourtenant-admin.sharepoint.com. Please connect to the tenant admin URL first and try again."); } } WriteObject(ex); } } }
protected override void ExecuteCmdlet() { if (ParameterSetName == "SITE") { var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); ServerRelativeUrl = UrlUtility.Combine(webUrl, SiteRelativeUrl); } var file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(ServerRelativeUrl)); ClientContext.Load(file, f => f.Name, f => f.ServerRelativePath); ClientContext.ExecuteQueryRetry(); if (Force || ShouldContinue(string.Format(Resources.RenameFile0To1, file.Name, TargetFileName), Resources.Confirm)) { var targetPath = string.Concat(file.ServerRelativePath.DecodedUrl.Remove(file.ServerRelativePath.DecodedUrl.Length - file.Name.Length), TargetFileName); file.MoveToUsingPath(ResourcePath.FromDecodedUrl(targetPath), OverwriteIfAlreadyExists ? MoveOperations.Overwrite : MoveOperations.None); ClientContext.ExecuteQueryRetry(); } }
protected override void ExecuteCmdlet() { var url = CurrentWeb.EnsureProperty(w => w.Url); var tenantUrl = UrlUtilities.GetTenantAdministrationUrl(ClientContext.Url); using (var tenantContext = ClientContext.Clone(tenantUrl)) { var tenant = new Tenant(tenantContext); var webUrl = url; if (!string.IsNullOrEmpty(WebUrl)) { try { var uri = new System.Uri(WebUrl); webUrl = WebUrl; } catch { ThrowTerminatingError(new ErrorRecord(new System.Exception("Invalid URL"), "INVALIDURL", ErrorCategory.InvalidArgument, WebUrl)); } } // Retrieve the site designs var designs = Identity.GetTenantSiteDesign(tenant); if (designs == null || designs.Length == 0) { throw new PSArgumentException("No site designs found matching the identity provided through Identity", nameof(Identity)); } foreach (var design in designs) { WriteVerbose($"Invoking site design '{design.Title}' ({design.Id})"); var results = tenant.ApplySiteDesign(webUrl, design.Id); tenantContext.Load(results); tenantContext.ExecuteQueryRetry(); WriteObject(results, true); } } }
protected override void ExecuteCmdlet() { CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); var sourceFolderUrl = UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, Folder); Folder sourceFolder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(sourceFolderUrl)); ClientContext.Load(sourceFolder, f => f.Name, f => f.ServerRelativeUrl); ClientContext.ExecuteQueryRetry(); var targetPath = string.Concat(TargetFolder, "/", sourceFolder.Name); sourceFolder.MoveToUsingPath(ResourcePath.FromDecodedUrl(targetPath)); ClientContext.ExecuteQueryRetry(); var folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(targetPath)); ClientContext.Load(folder, f => f.Name, f => f.ItemCount, f => f.TimeLastModified, f => f.ListItemAllFields); ClientContext.ExecuteQueryRetry(); WriteObject(folder); }
/// <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() { var serverRelativeWebUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant())) { ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl); } var definitions = CurrentWeb.GetWebParts(ServerRelativePageUrl); if (Identity != null) { if (Identity.Id != Guid.Empty) { var wpfound = from wp in definitions where wp.Id == Identity.Id select wp; var webPartDefinitions = wpfound as WebPartDefinition[] ?? wpfound.ToArray(); if (webPartDefinitions.Any()) { WriteObject(webPartDefinitions.FirstOrDefault()); } } else if (!string.IsNullOrEmpty(Identity.Title)) { var wpfound = from wp in definitions where wp.WebPart.Title == Identity.Title select wp; var webPartDefinitions = wpfound as WebPartDefinition[] ?? wpfound.ToArray(); if (webPartDefinitions.Any()) { WriteObject(webPartDefinitions.FirstOrDefault()); } } } else { WriteObject(definitions, true); } }
protected override void ExecuteCmdlet() { CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); var folderUrl = UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, Folder, Name); Folder folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl)); folder.EnsureProperty(f => f.Name); if (Force || ShouldContinue(string.Format(Resources.Delete0, folder.Name), Resources.Confirm)) { if (Recycle) { folder.Recycle(); } else { folder.DeleteObject(); } ClientContext.ExecuteQueryRetry(); } }
protected override void ExecuteCmdlet() { CurrentWeb.EnsureProperty(w => w.HasUniqueRoleAssignments); // Can only set the Request Access Emails if the web has unique permissions if (CurrentWeb.HasUniqueRoleAssignments) { if (Emails != null && Emails.Length > 0 && !Disabled) { if (Emails.Length > 1) { // Only one e-mail address can be configured to receive the access requests throw new ArgumentException(Resources.SetRequestAccessEmailsOnlyOneAddressAllowed, nameof(Emails)); } else { // Configure the one e-mail address to receive the access requests CurrentWeb.SetUseAccessRequestDefaultAndUpdate(false); CurrentWeb.EnableRequestAccess(Emails[0]); } } else { if (Disabled) { // Disable requesting access CurrentWeb.DisableRequestAccess(); } else { // Enable requesting access and set it to the default owners group CurrentWeb.EnableRequestAccess(); } } } }
private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName, ExtractConfiguration configuration) { CurrentWeb.EnsureProperty(w => w.Url); ProvisioningTemplateCreationInformation creationInformation = null; if (configuration != null) { creationInformation = configuration.ToCreationInformation(CurrentWeb); } else { creationInformation = new ProvisioningTemplateCreationInformation(CurrentWeb); } if (ParameterSpecified(nameof(Handlers))) { creationInformation.HandlersToProcess = Handlers; } if (ParameterSpecified(nameof(ExcludeHandlers))) { foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } creationInformation.HandlersToProcess = Handlers; } var extension = ""; if (packageName != null) { if (packageName.IndexOf(".", StringComparison.Ordinal) > -1) { extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower(); } else { packageName += ".pnp"; extension = ".pnp"; } } var fileSystemConnector = new FileSystemConnector(path, ""); if (extension == ".pnp") { creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector); } else if (extension == ".md") { creationInformation.FileConnector = fileSystemConnector; } else { creationInformation.FileConnector = fileSystemConnector; } #pragma warning disable 618 if (ParameterSpecified(nameof(PersistBrandingFiles))) { creationInformation.PersistBrandingFiles = PersistBrandingFiles; } #pragma warning restore 618 creationInformation.PersistPublishingFiles = PersistPublishingFiles; creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles; if (ParameterSpecified(nameof(IncludeSiteGroups))) { creationInformation.IncludeSiteGroups = IncludeSiteGroups; } creationInformation.IncludeTermGroupsSecurity = IncludeTermGroupsSecurity; creationInformation.IncludeSearchConfiguration = IncludeSearchConfiguration; if (ParameterSpecified(nameof(IncludeHiddenLists))) { creationInformation.IncludeHiddenLists = IncludeHiddenLists; } if (ParameterSpecified(nameof(IncludeAllPages))) { creationInformation.IncludeAllClientSidePages = IncludeAllPages; } creationInformation.SkipVersionCheck = SkipVersionCheck; if (ParameterSpecified(nameof(ContentTypeGroups)) && ContentTypeGroups != null) { creationInformation.ContentTypeGroupsToInclude = ContentTypeGroups.ToList(); } creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources; if (extension == ".pnp") { // if file is of pnp format, persist all files creationInformation.PersistBrandingFiles = true; creationInformation.PersistPublishingFiles = true; creationInformation.PersistMultiLanguageResources = true; } if (!string.IsNullOrEmpty(ResourceFilePrefix)) { creationInformation.ResourceFilePrefix = ResourceFilePrefix; } else { if (Out != null) { FileInfo fileInfo = new FileInfo(Out); var prefix = fileInfo.Name; // strip extension, if there is any var indexOfLastDot = prefix.LastIndexOf(".", StringComparison.Ordinal); if (indexOfLastDot > -1) { prefix = prefix.Substring(0, indexOfLastDot); } creationInformation.ResourceFilePrefix = prefix; } } if (ExtensibilityHandlers != null) { creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList(); } #pragma warning disable CS0618 // Type or member is obsolete if (NoBaseTemplate) { creationInformation.BaseTemplate = null; } else { creationInformation.BaseTemplate = CurrentWeb.GetBaseTemplate(); } #pragma warning restore CS0618 // Type or member is obsolete creationInformation.ProgressDelegate = (message, step, total) => { var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step)); WriteProgress(new ProgressRecord(0, $"Extracting Template from {CurrentWeb.Url}", message) { PercentComplete = percentage }); WriteProgress(new ProgressRecord(1, " ", " ") { RecordType = ProgressRecordType.Completed }); }; creationInformation.MessagesDelegate = (message, type) => { switch (type) { case ProvisioningMessageType.Warning: { WriteWarning(message); break; } case ProvisioningMessageType.Progress: { var activity = message; if (message.IndexOf("|") > -1) { var messageSplitted = message.Split('|'); if (messageSplitted.Length == 4) { var current = double.Parse(messageSplitted[2]); var total = double.Parse(messageSplitted[3]); subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.Activity = messageSplitted[0]; subProgressRecord.StatusDescription = messageSplitted[1]; subProgressRecord.PercentComplete = Convert.ToInt32((100 / total) * current); WriteProgress(subProgressRecord); } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } break; } case ProvisioningMessageType.Completed: { WriteProgress(new ProgressRecord(1, message, " ") { RecordType = ProgressRecordType.Completed }); break; } } }; if (IncludeAllTermGroups) { creationInformation.IncludeAllTermGroups = true; } else { if (IncludeSiteCollectionTermGroup) { creationInformation.IncludeSiteCollectionTermGroup = true; } } if (ParameterSpecified(nameof(ExcludeContentTypesFromSyndication))) { creationInformation.IncludeContentTypesFromSyndication = !ExcludeContentTypesFromSyndication.ToBool(); } if (ListsToExtract != null && ListsToExtract.Count > 0) { creationInformation.ListsToExtract.AddRange(ListsToExtract); } ProvisioningTemplate template = null; using (var provisioningContext = new PnPProvisioningContext(async(resource, scope) => { return(await TokenRetrieval.GetAccessTokenAsync(resource, scope)); // if (resource.ToLower().StartsWith("https://")) // { // var uri = new Uri(resource); // resource = uri.Authority; // } // if (resource.ToLower().Contains(".sharepoint.")) // { // // SharePoint // var authManager = PnPConnection.CurrentConnection.Context.GetContextSettings().AuthenticationManager; // if (authManager != null) // { // var token = await authManager.GetAccessTokenAsync($"https://{resource}"); // if (token != null) // { // return token; // } // } // } // // Get Azure AD Token // if (PnPConnection.CurrentConnection != null) // { // var graphAccessToken = await PnPConnection.CurrentConnection.TryGetAccessTokenAsync(Enums.TokenAudience.MicrosoftGraph); // if (graphAccessToken != null) // { // // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline // return graphAccessToken; // } // } // if (PnPConnection.CurrentConnection.PSCredential != null) // { // // Using normal credentials // return await TokenHandler.AcquireTokenAsync(resource, null); // } // else // { // // No token... // if (resource.ToLower().Contains(".sharepoint.")) // { // return null; // } // else // { // throw new PSInvalidOperationException($"Your template contains artifacts that require an access token for {resource}. Either connect with a clientid which the appropriate permissions, or use credentials with Connect-PnPOnline after providing consent to the PnP Management Shell application first by executing: Register-PnPManagementShellAccess. See https://pnp.github.io/powershell/articles/authentication.html"); // } // } })) { template = CurrentWeb.GetProvisioningTemplate(creationInformation); } // Set metadata for template, if any SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties); if (!OutputInstance) { var formatter = ProvisioningHelper.GetFormatter(schema); if (extension == ".pnp") { XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider( creationInformation.FileConnector as OpenXMLConnector); var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions); } else if (extension == ".md") { WriteWarning("The generation of a markdown report is work in progress, it will improve/grow with later releases."); ITemplateFormatter mdFormatter = new MarkdownPnPFormatter(); using (var outputStream = mdFormatter.ToFormattedTemplate(template)) { using (var fileStream = File.Create(Path.Combine(path, packageName))) { outputStream.Seek(0, SeekOrigin.Begin); outputStream.CopyTo(fileStream); fileStream.Close(); } } } else { if (Out != null) { XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, ""); provider.SaveAs(template, Path.Combine(path, packageName), formatter, TemplateProviderExtensions); } else { var outputStream = formatter.ToFormattedTemplate(template); var reader = new StreamReader(outputStream); WriteObject(reader.ReadToEnd()); } } } else { WriteObject(template); } }
private IEnumerable <object> GetContents(string FolderSiteRelativeUrl) { Folder targetFolder = null; if (ParameterSetName == ParameterSet_FOLDERSBYPIPE && Identity != null) { targetFolder = Identity.GetFolder(CurrentWeb); } else { string serverRelativeUrl = null; if (!string.IsNullOrEmpty(FolderSiteRelativeUrl)) { var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); serverRelativeUrl = UrlUtility.Combine(webUrl, FolderSiteRelativeUrl); } targetFolder = (string.IsNullOrEmpty(FolderSiteRelativeUrl)) ? CurrentWeb.RootFolder : CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); } IEnumerable <File> files = null; IEnumerable <Folder> folders = null; if (ItemType == "File" || ItemType == "All") { files = ClientContext.LoadQuery(targetFolder.Files).OrderBy(f => f.Name); if (!string.IsNullOrEmpty(ItemName)) { files = files.Where(f => f.Name.Equals(ItemName, StringComparison.InvariantCultureIgnoreCase)); } } if (ItemType == "Folder" || ItemType == "All" || Recursive) { folders = ClientContext.LoadQuery(targetFolder.Folders).OrderBy(f => f.Name); if (!string.IsNullOrEmpty(ItemName)) { folders = folders.Where(f => f.Name.Equals(ItemName, StringComparison.InvariantCultureIgnoreCase)); } } ClientContext.ExecuteQueryRetry(); IEnumerable <object> folderContent = null; switch (ItemType) { case "All": folderContent = folders.Concat <object>(files); break; case "Folder": folderContent = folders; break; default: folderContent = files; break; } if (Recursive && folders.Count() > 0) { foreach (var folder in folders) { var relativeUrl = folder.ServerRelativeUrl.Replace(CurrentWeb.ServerRelativeUrl, ""); var subFolderContents = GetContents(relativeUrl); folderContent = folderContent.Concat <object>(subFolderContents); } } return(folderContent); }
private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName) { CurrentWeb.EnsureProperty(w => w.Url); var creationInformation = new ProvisioningTemplateCreationInformation(CurrentWeb) { HandlersToProcess = Handlers.Lists }; var extension = ""; if (packageName != null) { if (packageName.IndexOf(".", StringComparison.Ordinal) > -1) { extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower(); } else { packageName += ".pnp"; extension = ".pnp"; } } var fileSystemConnector = new FileSystemConnector(path, ""); if (extension == ".pnp") { creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector); } else { creationInformation.FileConnector = fileSystemConnector; } creationInformation.ProgressDelegate = (message, step, total) => { var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step)); WriteProgress(new ProgressRecord(0, $"Extracting Template from {CurrentWeb.Url}", message) { PercentComplete = percentage }); }; creationInformation.MessagesDelegate = (message, type) => { switch (type) { case ProvisioningMessageType.Warning: { WriteWarning(message); break; } case ProvisioningMessageType.Progress: { var activity = message; if (message.IndexOf("|") > -1) { var messageSplitted = message.Split('|'); if (messageSplitted.Length == 4) { var current = double.Parse(messageSplitted[2]); var total = double.Parse(messageSplitted[3]); subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.Activity = messageSplitted[0]; subProgressRecord.StatusDescription = messageSplitted[1]; subProgressRecord.PercentComplete = Convert.ToInt32((100 / total) * current); WriteProgress(subProgressRecord); } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } break; } case ProvisioningMessageType.Completed: { WriteProgress(new ProgressRecord(1, message, " ") { RecordType = ProgressRecordType.Completed }); break; } } }; if (List != null && List.Count > 0) { creationInformation.ListsToExtract.AddRange(List); } var template = CurrentWeb.GetProvisioningTemplate(creationInformation); if (!OutputInstance) { var formatter = ProvisioningHelper.GetFormatter(schema); if (extension == ".pnp") { XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider( creationInformation.FileConnector as OpenXMLConnector); var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; provider.SaveAs(template, templateFileName, formatter, null); } else { if (Out != null) { XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, ""); provider.SaveAs(template, Path.Combine(path, packageName), formatter, null); } else { var outputStream = formatter.ToFormattedTemplate(template); var reader = new StreamReader(outputStream); WriteObject(reader.ReadToEnd()); } } } else { WriteObject(template); } }