diff --git a/CHANGELOG.md b/CHANGELOG.md index 943238b70..e6f4a62c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Added `Set-PnPSiteDocumentIdPrefix` which allows changing of the document id prefix on a site collection [#4765](https://github.com/pnp/powershell/pull/4765) - Added `Get-PnPMicrosoft365Roadmap` which allows retrieval of the Microsoft 365 Roadmap items [#4764](https://github.com/pnp/powershell/pull/4764) - Added `-Name` parameter to `Add-PnPApplicationCustomizer` cmdlet to allow for specifying the name of the application customizer [#4767](https://github.com/pnp/powershell/pull/4767) +- Added `Get-PnPTraceLog` cmdlet which allows reading from the detailed in memory logs of the PnP PowerShell cmdlet execution [#4794](https://github.com/pnp/powershell/pull/4794) ### Changed diff --git a/documentation/Clear-PnPTraceLog.md b/documentation/Clear-PnPTraceLog.md new file mode 100644 index 000000000..bcf62f120 --- /dev/null +++ b/documentation/Clear-PnPTraceLog.md @@ -0,0 +1,51 @@ +--- +Module Name: PnP.PowerShell +title: Clear-PnPTraceLog +schema: 2.0.0 +applicable: SharePoint Online +external help file: PnP.PowerShell.dll-Help.xml +online version: https://pnp.github.io/powershell/cmdlets/Clear-PnPTraceLog.html +--- + +# Clear-PnPTraceLog + +## SYNOPSIS +Clears the log stream in memory + +## SYNTAX + +```powershell +Clear-PnPTraceLog [-Verbose] +``` + +## DESCRIPTION +This clears the in memory stored log stream which was started with the [Start-PnPTraceLog -WriteToLogstream](Start-PnPTraceLog.md) cmdlet. It will not clear the log file if one was specified. + +## EXAMPLES + +### EXAMPLE 1 +```powershell +Clear-PnPTraceLog +``` + +This clears the in memory stored log stream + +## PARAMETERS + +### -Verbose +When provided, additional debug statements will be shown while executing the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## RELATED LINKS + +[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/documentation/Get-PnPTraceLog.md b/documentation/Get-PnPTraceLog.md new file mode 100644 index 000000000..e6a1cafd2 --- /dev/null +++ b/documentation/Get-PnPTraceLog.md @@ -0,0 +1,111 @@ +--- +Module Name: PnP.PowerShell +title: Get-PnPTraceLog +schema: 2.0.0 +applicable: SharePoint Online +external help file: PnP.PowerShell.dll-Help.xml +online version: https://pnp.github.io/powershell/cmdlets/Get-PnPTraceLog.html +--- + +# Get-PnPTraceLog + +## SYNOPSIS +Returns logged messages during the execution of PnP PowerShell cmdlets + +## SYNTAX + +### Log from file + +```powershell +Get-PnPTraceLog -Path [-Verbose] +``` +### Log from log stream + +```powershell +Get-PnPTraceLog [-Verbose] +``` + +## DESCRIPTION +This cmdlet returns the logged messages during the execution of PnP PowerShell cmdlets. It can return the messages from an in memory log stream or from a file. Note that you cannot read from a log file if it is currently in use to write to. In this case, you would first have to stop logging to it using [Stop-PnPTraceLog](Stop-PnPTraceLog.md) and then read the log file. The in memory log stream is always available. + +You can use [Start-PnPTraceLog](Start-PnPTraceLog.md) to start logging to a file and/or to an in memory stream. + +## EXAMPLES + +### EXAMPLE 1 +```powershell +Get-PnPTraceLog +``` + +This returns all items in the in memory stored log stream + +### EXAMPLE 2 +```powershell +Get-PnPTraceLog -Path "C:\temp\log.txt" +``` + +This returns all items from the log file stored at the provided location. Note that you cannot read from a log file if it is currently in use to write to. In this case, you would first have to stop logging to it using [Stop-PnPTraceLog](Stop-PnPTraceLog.md) and then read the log file. + +### EXAMPLE 3 +```powershell +Get-PnPTraceLog | Where-Object { $_.Level -eq "Error" } +``` + +This returns only logged items from the in memory stored log stream that have a level of "Error" + +### EXAMPLE 4 +```powershell +Get-PnPTraceLog | Where-Object { $_.CorrelationId -eq "5a6206a0-6c83-4446-9d1b-38c14f93cb60" } +``` + +This returns only logged items from the in memory stored log stream that happened during the execution of a PnP PowerShell cmdlet with the provided correlation id. This is useful to find out what happened during the execution of a specific cmdlet. Mind that the correlation id is an unique identifier for the cmdlet execution assigned by PnP PowerShell and is not the same as the correlation id of a SharePoint operation. + +### EXAMPLE 5 +```powershell +Get-PnPTraceLog | Sort-Object -Property EllapsedMilliseconds -Descending -Top 10 | Select EllapsedMilliseconds, Source, Message +``` + +Returns the 10 longest running operations from the in memory stored log stream. An operation is an action within the execution of a cmdlet. The output is sorted by the time it took to complete the operation with the longest execution at the top. The output shows the ellapsed time in milliseconds taken by a single operation, the cmdlet that was executed and the message that was logged. + +### EXAMPLE 6 +```powershell +Get-PnPTraceLog | Group-Object -Property CorrelationId | ForEach-Object { [pscustomobject]@{ Started = ($_.Group | Select -First 1).TimeStamp; Ended = ($_.Group | Select -Last 1).TimeStamp; Cmdlet = $_.Group[0].Source; TimeTaken = ($_.Group | Measure-Object -Property EllapsedMilliseconds -Sum).Sum; Logs = $_.Group }} | Sort-Object -Property TimeTaken -Descending -Top 5 | Select Started, Cmdlet, TimeTaken +``` + +Returns the top 5 longest running cmdlets from the in memory stored log stream. The output is sorted by the TimeTaken property in descending order which shows the total execution time of a single cmdlet. The output contains the time the cmdlet started executing, the cmdlet that was executed and the total time it took to execute the cmdlet. From there it is easy to examine all the individual logs collected during the execution of that single cmdlet. + +## PARAMETERS + +### -Path +The path to the log file. If not provided, the cmdlet will return the in memory log stream. + +Note that you cannot read from a log file if it is currently in use to write to. In this case, you would first have to stop logging to it using [Stop-PnPTraceLog](Stop-PnPTraceLog.md) and then read the log file. + +```yaml +Type: String +Parameter Sets: Log from file + +Required: True +Position: Named +Default value: None +Accept pipeline input: True +Accept wildcard characters: False +``` + +### -Verbose +When provided, additional debug statements will be shown while executing the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## RELATED LINKS + +[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/documentation/Start-PnPTraceLog.md b/documentation/Start-PnPTraceLog.md index a8d819815..d09e14780 100644 --- a/documentation/Start-PnPTraceLog.md +++ b/documentation/Start-PnPTraceLog.md @@ -15,13 +15,26 @@ Starts log tracing ## SYNTAX ```powershell -Start-PnPTraceLog [-Path ] [-Level ] [-AutoFlush ] [-WriteToConsole ] +Start-PnPTraceLog [-Path ] [-Level ] [-AutoFlush ] [-WriteToConsole ] [-WriteToLogStream ] ``` - ## DESCRIPTION Starts .NET tracelogging. Many cmdlets output detailed trace information when executed. Turn on the trace log with this cmdlet, optionally specify the level. By default the level is set to 'Information', but you will receive more detail by setting the level to 'Debug'. +You can look at the logged data using [Get-PnPTraceLog](Get-PnPTraceLog.md). + +The logged data contains the following information in the following order: + +- Timestamp +- Source +- Thread ID +- Log level +- Message +- Elapsed time in milliseconds since the last log entry for the same cmdlet execution +- Correlation ID which is an unique identifier per executed cmdlet so you can filter the log for everything logged during a specific cmdlet execution + +Beware that the logged data can be quite verbose, especially when the level is set to 'Debug'. When logging in memory, it can take up a lot of memory. When logging to a file, it can take up a lot of disk space. So be careful when using this in production environments and only use it when you need to troubleshoot something or are aware of the consequences. + ## EXAMPLES ### EXAMPLE 1 @@ -38,12 +51,19 @@ Start-PnPTraceLog -Path ./TraceOutput.txt -Level Debug This turns on trace logging to the file 'TraceOutput.txt' and will capture all events. +### EXAMPLE 3 +```powershell +Start-PnPTraceLog -WriteToConsole -WriteToLogStream -Level Debug +``` + +This turns on trace logging to the console and in memory stream in which you are running your PowerShell script and will capture all events. + ### EXAMPLE 3 ```powershell Start-PnPTraceLog -WriteToConsole -Level Debug ``` -This turns on trace logging to console in which you are running your PowerShell script and will capture all events. +This turns on trace logging to the console in which you are running your PowerShell script and will capture all events. ## PARAMETERS @@ -104,6 +124,20 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -WriteToLogStream +Write the trace log to the in memory stream. Use [Get-PnPTraceLog](Get-PnPTraceLog.md) to read the log stream. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ## RELATED LINKS [Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/documentation/Stop-PnPTraceLog.md b/documentation/Stop-PnPTraceLog.md index 22a167147..e7f82c4fc 100644 --- a/documentation/Stop-PnPTraceLog.md +++ b/documentation/Stop-PnPTraceLog.md @@ -10,17 +10,19 @@ online version: https://pnp.github.io/powershell/cmdlets/Set-PnPTraceLog.html # Stops-PnPTraceLog ## SYNOPSIS -Stops log tracing and flushes the log buffer if any items in there. +Stops all log tracing and flushes the log buffer if any items in there. ## SYNTAX ```powershell -Stop-PnPTraceLog +Stop-PnPTraceLog [-StopFileLogging ] [-StopConsoleLogging ] [-StopLogStreamLogging ] [-Verbose] ``` - ## DESCRIPTION -Stops .NET tracelogging. Many cmdlets output detailed trace information when executed. Turn on the trace log with Start-PnPTraceLog, optionally specify the level. By default the level is set to 'Information', but you will receive more detail by setting the level to 'Debug'. +Stops PnP PowerShell tracelogging to specific targets. By default, all logging is stopped. You can use the parameters to stop specific logging targets only. + +You can turn on the trace log with [Start-PnPTraceLog](Start-PnPTraceLog.md). +You can look at the logged data using [Get-PnPTraceLog](Get-PnPTraceLog.md). ## EXAMPLES @@ -29,9 +31,61 @@ Stops .NET tracelogging. Many cmdlets output detailed trace information when exe Stop-PnPTraceLog ``` -This turns off trace logging +This turns off all trace logging -## RELATED LINKS +## EXAMPLES + +### EXAMPLE 2 +```powershell +Stop-PnPTraceLog -StopFileLogging -StopConsoleLogging +``` + +This turns off trace logging to file and console, but keeps the other logging options active. + +## PARAMETERS + +### -StopConsoleLogging +Allows you to specifically stop logging to the console while keeping the other logging options active. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) -[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StopFileLogging +Allows you to specifically stop logging to a file while keeping the other logging options active. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -StopLogStreamLogging +Allows you to specifically stop logging to the in memory log stream while keeping the other logging options active. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +## RELATED LINKS +[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/documentation/Write-PnPTraceLog.md b/documentation/Write-PnPTraceLog.md new file mode 100644 index 000000000..779bc9efe --- /dev/null +++ b/documentation/Write-PnPTraceLog.md @@ -0,0 +1,152 @@ +--- +Module Name: PnP.PowerShell +title: Write-PnPTraceLog +schema: 2.0.0 +applicable: SharePoint Online +external help file: PnP.PowerShell.dll-Help.xml +online version: https://pnp.github.io/powershell/cmdlets/Write-PnPTraceLog.html +--- + +# Write-PnPTraceLog + +## SYNOPSIS +Allows logging your own messages during the execution of PnP PowerShell cmdlets + +## SYNTAX + +### Log from file + +```powershell +Write-PnPTraceLog -Path [-Verbose] +``` +### Log from log stream + +```powershell +Write-PnPTraceLog [-Verbose] +``` + +## DESCRIPTION +This cmdlet allows logging of your own messages in line with the PnPTraceLog cmdlets that allow logging what happens behind the scenes of the execution of PnP PowerShell cmdlets. This allows you to inject your own custom logging along with the built in logging to get a complete and chronoligal log of the execution of the cmdlets in your scripts. + +Look at [Start-PnPTraceLog](Start-PnPTraceLog.md) to see how to start logging to a file and/or to an in memory stream. +You can use [Get-PnPTraceLog](Get-PnPTraceLog.md) to read from the log file or the in memory stream. + +## EXAMPLES + +### EXAMPLE 1 +```powershell +Write-PnPTraceLog "Hello World" +``` + +This logs the message "Hello World" as an informational message to the built in logging. + +### EXAMPLE 2 +```powershell +Write-PnPTraceLog "Hello World" -Level Warning +``` + +This logs the message "Hello World" as an warning message to the built in logging. + +### EXAMPLE 3 +```powershell +Write-PnPTraceLog "Hello World" -Level Error -Source "MyScript" +``` + +This logs the message "Hello World" as an error message to the built in logging with a source of "MyScript". The source is used to identify the cmdlet that was executed when the log was created. This is useful to identify which part of your script was executing when the log was created. + +### EXAMPLE 4 +```powershell +Write-PnPTraceLog "Hello World" -Level Debug -Source "MyScript" -CorrelationId "5a6206a0-6c83-4446-9d1b-38c14f93cb60" -EllapsedMilliseconds 1000 +``` + +This is the most complete example. It logs the message "Hello World" as a debug message to the built in logging with a source of "MyScript", a correlation id of "5a6206a0-6c83-4446-9d1b-38c14f93cb60" and an ellapsed time of 1000 milliseconds. The correlation id is used to identify the set of operations that were executed when the log was created. The ellapsed time is used to identify how long the operation took to complete. You can provide your own measurements to define this value. If you omit the ellapsed time, the cmdlet will try to define the execution time based on the last logged entry. + +## PARAMETERS + +### -CorrelationId +An optional GUID as an unique identifier for the cmdlet execution. This is useful to identify which part of your script was executing when the log was created. If not provided, it will leave the value empty. + +```yaml +Type: Guid +Parameter Sets: (All) + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EllapsedMilliseconds +You can optionaly provide the ellapsed time in milliseconds. This is the time that was taken to execute the operation. If you omit this parameter, the cmdlet will try to define the execution time based on the last logged entry. + +```yaml +Type: Long +Parameter Sets: (All) + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Level +The level to log your message under. Options are: Verbose, Information, Warning, Error and Debug. It will log it both to the default PowerShell its logging equivallent such as Write-Warning, Write-Error, Write-Verbose, and to the PnPTraceLog logging. If not provided, it will default to Information. + +```yaml +Type: Framework.Diagnostics.LogLevel +Parameter Sets: (All) + +Required: False +Position: Named +Default value: Information +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Message +The message to log. This is the message that will be logged to the log file or the in memory stream. + +```yaml +Type: String +Parameter Sets: (All) + +Required: True +Position: Named +Default value: None +Accept pipeline input: True +Accept wildcard characters: False +``` + +### -Source +The source of the log. This is the source that will be logged to the log file or the in memory stream. This is useful to identify which part of your script was executing when the log was created. + +```yaml +Type: String +Parameter Sets: (All) + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Verbose +When provided, additional debug statements will be shown while executing the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## RELATED LINKS + +[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/resources/PnP.PowerShell.Format.ps1xml b/resources/PnP.PowerShell.Format.ps1xml index cf7b8bb0f..8484edefc 100644 --- a/resources/PnP.PowerShell.Format.ps1xml +++ b/resources/PnP.PowerShell.Format.ps1xml @@ -3157,6 +3157,50 @@ - + + + CheckedOutFile + + PnP.PowerShell.Commands.Utilities.Logging.TraceLogEntry + + + + + + left + + + + left + + + + left + + + + left + + + + + + + TimeStamp + + + Source + + + Level + + + Message + + + + + + \ No newline at end of file diff --git a/src/Commands/Admin/AddTenantRestrictedSearchAllowedList.cs b/src/Commands/Admin/AddTenantRestrictedSearchAllowedList.cs index 5938e5d2a..036dacc89 100644 --- a/src/Commands/Admin/AddTenantRestrictedSearchAllowedList.cs +++ b/src/Commands/Admin/AddTenantRestrictedSearchAllowedList.cs @@ -46,7 +46,7 @@ protected override void ExecuteCmdlet() if(_sitelist.Count > 100) { - WriteWarning($"The maximum number of sites that can be added to the allowed list is 100. You have specified {_sitelist.Count} sites. Will try to add them anyway."); + LogWarning($"The maximum number of sites that can be added to the allowed list is 100. You have specified {_sitelist.Count} sites. Will try to add them anyway."); } Tenant.AddSPORestrictedSearchAllowedList(_sitelist); diff --git a/src/Commands/Admin/AddTenantTheme.cs b/src/Commands/Admin/AddTenantTheme.cs index a8f34a0ec..ee03fc5e2 100644 --- a/src/Commands/Admin/AddTenantTheme.cs +++ b/src/Commands/Admin/AddTenantTheme.cs @@ -41,7 +41,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new Exception($"Theme exists"), "THEMEEXISTS", ErrorCategory.ResourceExists, Identity.Name)); + LogError("Theme exists"); } } else diff --git a/src/Commands/Admin/GetSiteCollectionAppCatalog.cs b/src/Commands/Admin/GetSiteCollectionAppCatalog.cs index c4f152dbe..05353650e 100644 --- a/src/Commands/Admin/GetSiteCollectionAppCatalog.cs +++ b/src/Commands/Admin/GetSiteCollectionAppCatalog.cs @@ -23,7 +23,7 @@ public class GetSiteCollectionAppCatalog : PnPSharePointOnlineAdminCmdlet protected override void ExecuteCmdlet() { - WriteVerbose("Retrieving all site collection App Catalogs from SharePoint Online"); + LogDebug("Retrieving all site collection App Catalogs from SharePoint Online"); var appCatalogsCsom = AdminContext.Web.TenantAppCatalog.SiteCollectionAppCatalogsSites; AdminContext.Load(appCatalogsCsom); @@ -38,20 +38,20 @@ protected override void ExecuteCmdlet() } ).ToList(); - WriteVerbose($"{appCatalogsLocalModel.Count} site collection App Catalog{(appCatalogsLocalModel.Count != 1 ? "s have" : " has")} been retrieved"); + LogDebug($"{appCatalogsLocalModel.Count} site collection App Catalog{(appCatalogsLocalModel.Count != 1 ? "s have" : " has")} been retrieved"); if (CurrentSite.ToBool()) { ClientContext.Site.EnsureProperties(s => s.Id); - WriteVerbose($"Filtering down to only the current site at {Connection.Url} with ID {ClientContext.Site.Id}"); + LogDebug($"Filtering down to only the current site at {Connection.Url} with ID {ClientContext.Site.Id}"); var currentSite = appCatalogsLocalModel.FirstOrDefault(a => a.SiteID.HasValue && a.SiteID.Value == ClientContext.Site.Id); appCatalogsLocalModel.Clear(); if (currentSite == null) { - WriteVerbose($"Current site at {Connection.Url} with ID {ClientContext.Site.Id} does not have a site collection App Catalog on it"); + LogDebug($"Current site at {Connection.Url} with ID {ClientContext.Site.Id} does not have a site collection App Catalog on it"); return; } @@ -60,7 +60,7 @@ protected override void ExecuteCmdlet() if(SkipUrlValidation.ToBool()) { - WriteVerbose($"Skipping URL validation since the {nameof(SkipUrlValidation)} flag has been provided"); + LogDebug($"Skipping URL validation since the {nameof(SkipUrlValidation)} flag has been provided"); WriteObject(appCatalogsLocalModel, true); return; } @@ -72,7 +72,7 @@ protected override void ExecuteCmdlet() { try { - WriteVerbose($"Validating site collection App Catalog at {appCatalogLocalModel.AbsoluteUrl}"); + LogDebug($"Validating site collection App Catalog at {appCatalogLocalModel.AbsoluteUrl}"); // Deleted sites throw either an exception or return null appCatalogLocalModel.AbsoluteUrl = Tenant.GetSitePropertiesById(appCatalogLocalModel.SiteID.Value, false, Connection.TenantAdminUrl).Url; @@ -84,12 +84,12 @@ protected override void ExecuteCmdlet() { if (!ExcludeDeletedSites.ToBool()) { - WriteVerbose($"Site collection App Catalog at {appCatalogLocalModel.AbsoluteUrl} regards a site that has been deleted"); + LogDebug($"Site collection App Catalog at {appCatalogLocalModel.AbsoluteUrl} regards a site that has been deleted"); results.Add(appCatalogLocalModel); } else { - WriteVerbose($"Site collection App Catalog at {appCatalogLocalModel.AbsoluteUrl} regards a site that has been deleted. Since the {nameof(ExcludeDeletedSites)} flag has been provided, it will not be included in the results."); + LogDebug($"Site collection App Catalog at {appCatalogLocalModel.AbsoluteUrl} regards a site that has been deleted. Since the {nameof(ExcludeDeletedSites)} flag has been provided, it will not be included in the results."); } continue; diff --git a/src/Commands/Admin/GetStorageEntity.cs b/src/Commands/Admin/GetStorageEntity.cs index 7a5de2675..dad59c44d 100644 --- a/src/Commands/Admin/GetStorageEntity.cs +++ b/src/Commands/Admin/GetStorageEntity.cs @@ -48,7 +48,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Site Collection App Catalog is not available on this site."); + LogWarning("Site Collection App Catalog is not available on this site."); } } else @@ -82,7 +82,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Tenant app catalog is not available on this tenant."); + LogWarning("Tenant app catalog is not available on this tenant."); } } diff --git a/src/Commands/Admin/GetTenantDeletedSite.cs b/src/Commands/Admin/GetTenantDeletedSite.cs index bb70a2bf1..987d97a5d 100644 --- a/src/Commands/Admin/GetTenantDeletedSite.cs +++ b/src/Commands/Admin/GetTenantDeletedSite.cs @@ -63,7 +63,7 @@ protected override void ExecuteCmdlet() } if (!flag2 && flag3) { - WriteWarning("More sites are available"); + LogWarning("More sites are available"); } } else @@ -78,7 +78,7 @@ protected override void ExecuteCmdlet() } catch (ServerException e) when (e.ServerErrorTypeName.Equals("Microsoft.SharePoint.Client.UnknownError", StringComparison.InvariantCultureIgnoreCase)) { - WriteVerbose($"No sitecollection found in the tenant recycle bin with the Url {Identity.Url}"); + LogDebug($"No sitecollection found in the tenant recycle bin with the Url {Identity.Url}"); } } } diff --git a/src/Commands/Admin/GetTenantInfo.cs b/src/Commands/Admin/GetTenantInfo.cs index 599bf47f6..8635bc101 100644 --- a/src/Commands/Admin/GetTenantInfo.cs +++ b/src/Commands/Admin/GetTenantInfo.cs @@ -31,11 +31,11 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("Specify either DomainName or TenantId, but not both."); } - WriteVerbose("Acquiring access token for Microsoft Graph to look up Tenant"); + LogDebug("Acquiring access token for Microsoft Graph to look up Tenant"); //var graphAccessToken = TokenHandler.GetAccessToken(this, $"https://{Connection.GraphEndPoint}/.default", Connection); var requestUrl = BuildRequestUrl(); - WriteVerbose($"Making call to {requestUrl} to request tenant information"); + LogDebug($"Making call to {requestUrl} to request tenant information"); var results = this.RequestHelper.Get(requestUrl); WriteObject(results, true); } diff --git a/src/Commands/Admin/GetTimeZoneId.cs b/src/Commands/Admin/GetTimeZoneId.cs index 604ab8b2f..bd75ccae1 100644 --- a/src/Commands/Admin/GetTimeZoneId.cs +++ b/src/Commands/Admin/GetTimeZoneId.cs @@ -3,11 +3,12 @@ using System.Collections.Generic; using System.Linq; using System.Management.Automation; +using PnP.PowerShell.Commands.Base; namespace PnP.PowerShell.Commands { [Cmdlet(VerbsCommon.Get, "PnPTimeZoneId")] - public class GetTimeZoneId : PSCmdlet + public class GetTimeZoneId : BasePSCmdlet { [Parameter(Mandatory = false, Position = 0)] public string Match; diff --git a/src/Commands/Admin/InvokeSiteSwap.cs b/src/Commands/Admin/InvokeSiteSwap.cs index 5ed26d45d..f5cc9bd30 100644 --- a/src/Commands/Admin/InvokeSiteSwap.cs +++ b/src/Commands/Admin/InvokeSiteSwap.cs @@ -30,7 +30,7 @@ protected override void ExecuteCmdlet() { var includeSmartGestures = !DisableRedirection; - WriteVerbose($"Invoking site swap with source {SourceUrl}, target {TargetUrl} and archive {ArchiveUrl}"); + LogDebug($"Invoking site swap with source {SourceUrl}, target {TargetUrl} and archive {ArchiveUrl}"); var operation = this.Tenant.SwapSiteWithSmartGestureOption(SourceUrl, TargetUrl, ArchiveUrl, includeSmartGestures); AdminContext.Load(operation); diff --git a/src/Commands/Admin/NewContainerType.cs b/src/Commands/Admin/NewContainerType.cs index 4900ea695..218123ddb 100644 --- a/src/Commands/Admin/NewContainerType.cs +++ b/src/Commands/Admin/NewContainerType.cs @@ -44,14 +44,14 @@ protected override void ExecuteCmdlet() SPContainerTypeProperties sPContainerTypeProperties; if (!ParameterSpecified(nameof(TrialContainerType)) || !TrialContainerType.ToBool()) { - WriteWarning($"Creation of standard container types is not yet supported. This will be enabled in the future. For now, only trial container types can be created by adding the -{nameof(TrialContainerType)} parameter."); + LogWarning($"Creation of standard container types is not yet supported. This will be enabled in the future. For now, only trial container types can be created by adding the -{nameof(TrialContainerType)} parameter."); return; // NOTICE: // Currently disabled by request of the product group as it doesn't work reliably yet // Once the official endpoint to create standard container types is available, this code can be enabled again and will point to the proper API to use - // WriteVerbose("Creating a standard container type"); + // LogDebug("Creating a standard container type"); // sPContainerTypeProperties = new SPContainerTypeProperties // { @@ -65,7 +65,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose("Creating a trial container type"); + LogDebug("Creating a trial container type"); sPContainerTypeProperties = new SPContainerTypeProperties { @@ -93,7 +93,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose("Failed to create container type"); + LogDebug("Failed to create container type"); } } } diff --git a/src/Commands/Admin/NewSite.cs b/src/Commands/Admin/NewSite.cs index edd0f1f37..ac4627ad8 100644 --- a/src/Commands/Admin/NewSite.cs +++ b/src/Commands/Admin/NewSite.cs @@ -190,12 +190,12 @@ protected override void ExecuteCmdlet() } catch (Exception ex) { - WriteError(ex, ErrorCategory.WriteError); + LogError(ex); } } else { - WriteError(new PSInvalidOperationException("Creating a new teamsite requires an underlying Microsoft 365 group. In order to create this we need to acquire an access token for the Microsoft Graph. This is not possible using ACS App Only connections."), ErrorCategory.SecurityError); + LogError(new PSInvalidOperationException("Creating a new teamsite requires an underlying Microsoft 365 group. In order to create this we need to acquire an access token for the Microsoft Graph. This is not possible using ACS App Only connections.")); } } else diff --git a/src/Commands/Admin/RegisterAppCatalogSite.cs b/src/Commands/Admin/RegisterAppCatalogSite.cs index 006d522f9..6bb8d18ba 100644 --- a/src/Commands/Admin/RegisterAppCatalogSite.cs +++ b/src/Commands/Admin/RegisterAppCatalogSite.cs @@ -22,7 +22,7 @@ public class RegisterAppCatalogSite : PnPSharePointOnlineAdminCmdlet protected override void ExecuteCmdlet() { - WriteWarning("Notice that this cmdlet can take considerate time to finish executing."); + LogWarning("Notice that this cmdlet can take considerate time to finish executing."); Tenant.EnsureAppCatalogAsync(Url, Owner, TimeZoneId, Force).GetAwaiter().GetResult(); } } diff --git a/src/Commands/Admin/RemoveHomeSite.cs b/src/Commands/Admin/RemoveHomeSite.cs index 4dff9fbae..751b9ca19 100644 --- a/src/Commands/Admin/RemoveHomeSite.cs +++ b/src/Commands/Admin/RemoveHomeSite.cs @@ -24,7 +24,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("There is currently not site collection set as a home site in your tenant."); + LogWarning("There is currently not site collection set as a home site in your tenant."); } } } diff --git a/src/Commands/Admin/RemoveStorageEntity.cs b/src/Commands/Admin/RemoveStorageEntity.cs index fb1d8acb3..c9a2bb52f 100644 --- a/src/Commands/Admin/RemoveStorageEntity.cs +++ b/src/Commands/Admin/RemoveStorageEntity.cs @@ -29,7 +29,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Tenant app catalog is not available on this tenant."); + LogWarning("Tenant app catalog is not available on this tenant."); } } else @@ -44,7 +44,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Site Collection App Catalog is not available on this site."); + LogWarning("Site Collection App Catalog is not available on this site."); } } } diff --git a/src/Commands/Admin/RemoveTenantRestrictedSearchAllowedList.cs b/src/Commands/Admin/RemoveTenantRestrictedSearchAllowedList.cs index 2d79766a1..e6a63f57d 100644 --- a/src/Commands/Admin/RemoveTenantRestrictedSearchAllowedList.cs +++ b/src/Commands/Admin/RemoveTenantRestrictedSearchAllowedList.cs @@ -46,7 +46,7 @@ protected override void ExecuteCmdlet() if(_sitelist.Count > 100) { - WriteWarning($"The maximum number of sites that can be added to the allowed list is 100. You have specified {_sitelist.Count} sites. Will try to add them anyway."); + LogWarning($"The maximum number of sites that can be added to the allowed list is 100. You have specified {_sitelist.Count} sites. Will try to add them anyway."); } Tenant.RemoveSPORestrictedSearchAllowedList(_sitelist); diff --git a/src/Commands/Admin/RestoreDeletedContainer.cs b/src/Commands/Admin/RestoreDeletedContainer.cs index caa7f183e..d5e61cc21 100644 --- a/src/Commands/Admin/RestoreDeletedContainer.cs +++ b/src/Commands/Admin/RestoreDeletedContainer.cs @@ -18,10 +18,10 @@ protected override void ExecuteCmdlet() { if (Force || ShouldContinue($"Restore container {Identity}?", Properties.Resources.Confirm)) { - WriteVerbose($"Restoring container {Identity}"); + LogDebug($"Restoring container {Identity}"); Tenant.RestoreSPODeletedContainerByContainerId(Identity); AdminContext.ExecuteQueryRetry(); - WriteVerbose($"Restored container {Identity}"); + LogDebug($"Restored container {Identity}"); } } } diff --git a/src/Commands/Admin/RestoreTenantSite.cs b/src/Commands/Admin/RestoreTenantSite.cs index 45dad33f2..94c349d99 100644 --- a/src/Commands/Admin/RestoreTenantSite.cs +++ b/src/Commands/Admin/RestoreTenantSite.cs @@ -30,7 +30,7 @@ protected override void ExecuteCmdlet() { if (Force || ShouldContinue($"Restore site collection {Identity.Url}?", Properties.Resources.Confirm)) { - WriteVerbose($"Restoring site collection {Identity.Url}"); + LogDebug($"Restoring site collection {Identity.Url}"); SpoOperation spoOperation = Tenant.RestoreDeletedSite(Identity.Url); AdminContext.Load(spoOperation); diff --git a/src/Commands/Admin/RevokeUserSession.cs b/src/Commands/Admin/RevokeUserSession.cs index 2b3f345c8..ea0b9a049 100644 --- a/src/Commands/Admin/RevokeUserSession.cs +++ b/src/Commands/Admin/RevokeUserSession.cs @@ -24,27 +24,27 @@ protected override void ExecuteCmdlet() { case SPOUserSessionRevocationState.FeatureDisabled: { - WriteWarning("This cmdlet will be available in the future, but is not ready for use in your organization yet."); + LogWarning("This cmdlet will be available in the future, but is not ready for use in your organization yet."); break; } case SPOUserSessionRevocationState.Failure: { - WriteWarning($"Sorry, something went wrong and we could not sign out {User} from any device."); + LogWarning($"Sorry, something went wrong and we could not sign out {User} from any device."); break; } case SPOUserSessionRevocationState.InstantaneousSuccess: { - WriteWarning($"We succesfully signed out {User} from all devices."); + LogWarning($"We succesfully signed out {User} from all devices."); break; } case SPOUserSessionRevocationState.NonInstantaneousSuccess: { - WriteWarning($"It can take up to an hour to sign out {User} from all devices."); + LogWarning($"It can take up to an hour to sign out {User} from all devices."); break; } case SPOUserSessionRevocationState.UserNotFound: { - WriteWarning($"We could not find the user {User}. Check for typos and try again."); + LogWarning($"We could not find the user {User}. Check for typos and try again."); break; } default: diff --git a/src/Commands/Admin/SetOrgAssetsLibrary.cs b/src/Commands/Admin/SetOrgAssetsLibrary.cs index d1edd664a..63fb44d2b 100644 --- a/src/Commands/Admin/SetOrgAssetsLibrary.cs +++ b/src/Commands/Admin/SetOrgAssetsLibrary.cs @@ -26,27 +26,27 @@ protected override void ExecuteCmdlet() { if(ParameterSpecified(nameof(IsCopilotSearchable)) && ParameterSpecified(nameof(OrgAssetType)) && ParameterSpecified(nameof(ThumbnailUrl))) { - WriteVerbose("Setting org assets library with thumbnail url, organizational asset type and copilot searchable"); + LogDebug("Setting org assets library with thumbnail url, organizational asset type and copilot searchable"); Tenant.SetOrgAssetsWithConfig(LibraryUrl, ThumbnailUrl, OrgAssetType.Value, new OrgAssetsLibraryConfigParam { IsCopilotSearchable = IsCopilotSearchable.Value}); } else if(ParameterSpecified(nameof(IsCopilotSearchable)) && ParameterSpecified(nameof(OrgAssetType))) { - WriteVerbose("Setting org assets library with organizational asset type and copilot searchable"); + LogDebug("Setting org assets library with organizational asset type and copilot searchable"); Tenant.SetOrgAssetsWithConfig(LibraryUrl, null, OrgAssetType.Value, new OrgAssetsLibraryConfigParam { IsCopilotSearchable = IsCopilotSearchable.Value}); } else if(ParameterSpecified(nameof(OrgAssetType)) && ParameterSpecified(nameof(ThumbnailUrl))) { - WriteVerbose("Setting org assets library with thumbnail url and organizational asset type"); + LogDebug("Setting org assets library with thumbnail url and organizational asset type"); Tenant.SetOrgAssetsWithType(LibraryUrl, ThumbnailUrl, OrgAssetType.Value); } else if(ParameterSpecified(nameof(OrgAssetType))) { - WriteVerbose("Setting org assets library with organizational asset type"); + LogDebug("Setting org assets library with organizational asset type"); Tenant.SetOrgAssetsWithType(LibraryUrl, null, OrgAssetType.Value); } else if(ParameterSpecified(nameof(ThumbnailUrl))) { - WriteVerbose("Setting org assets library with thumbnail url"); + LogDebug("Setting org assets library with thumbnail url"); Tenant.SetOrgAssets(LibraryUrl, ThumbnailUrl); } AdminContext.ExecuteQueryRetry(); diff --git a/src/Commands/Admin/SetSiteArchiveState.cs b/src/Commands/Admin/SetSiteArchiveState.cs index 6ab450f20..d833fbaa4 100644 --- a/src/Commands/Admin/SetSiteArchiveState.cs +++ b/src/Commands/Admin/SetSiteArchiveState.cs @@ -51,7 +51,7 @@ protected override void ExecuteCmdlet() { case "FullyArchived": { - WriteWarning("Reactivating a site from \"Archived\" state is a paid operation. It can take upto 24hrs for the site to be reactivated. Performing the operation \"Reactivate Archived site\" on target."); + LogWarning("Reactivating a site from \"Archived\" state is a paid operation. It can take upto 24hrs for the site to be reactivated. Performing the operation \"Reactivate Archived site\" on target."); if (Force || ShouldContinue(Identity.Url, Properties.Resources.Confirm)) { spoOperation = Tenant.UnarchiveSiteByUrl(Identity.Url); diff --git a/src/Commands/Admin/SetStorageEntity.cs b/src/Commands/Admin/SetStorageEntity.cs index 638a355f3..7144cb08a 100644 --- a/src/Commands/Admin/SetStorageEntity.cs +++ b/src/Commands/Admin/SetStorageEntity.cs @@ -39,7 +39,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Tenant app catalog is not available on this tenant."); + LogWarning("Tenant app catalog is not available on this tenant."); } } else @@ -54,7 +54,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Site Collection App Catalog is not available on this site."); + LogWarning("Site Collection App Catalog is not available on this site."); } } } diff --git a/src/Commands/Admin/SetTenant.cs b/src/Commands/Admin/SetTenant.cs index 04c4df9cc..7145cbf64 100644 --- a/src/Commands/Admin/SetTenant.cs +++ b/src/Commands/Admin/SetTenant.cs @@ -664,7 +664,7 @@ protected override void ExecuteCmdlet() Tenant.EnsureProperty(t => t.SharingCapability); if (Tenant.SharingCapability != SharingCapabilities.ExternalUserAndGuestSharing) { - WriteWarning("Warning: anonymous links are not enabled on your tenant. Enable them with SharingCapability."); + LogWarning("Warning: anonymous links are not enabled on your tenant. Enable them with SharingCapability."); } if (RequireAnonymousLinksExpireInDays.Value != 0 && (RequireAnonymousLinksExpireInDays.Value < 1 || RequireAnonymousLinksExpireInDays.Value > 730)) { @@ -686,18 +686,18 @@ protected override void ExecuteCmdlet() { if (!Tenant.RequireAcceptingAccountMatchInvitedAccount) { - WriteWarning("We automatically enabled RequireAcceptingAccountMatchInvitedAccount because you selected to limit external sharing using domains."); + LogWarning("We automatically enabled RequireAcceptingAccountMatchInvitedAccount because you selected to limit external sharing using domains."); Tenant.RequireAcceptingAccountMatchInvitedAccount = true; } Tenant.SharingAllowedDomainList = SharingAllowedDomainList; modified = true; if ((SharingDomainRestrictionMode == null && Tenant.SharingDomainRestrictionMode != SharingDomainRestrictionModes.AllowList) || SharingDomainRestrictionMode == SharingDomainRestrictionModes.None) { - WriteWarning("You must set SharingDomainRestrictionMode to AllowList in order to have the list of domains you configured for SharingAllowedDomainList to take effect."); + LogWarning("You must set SharingDomainRestrictionMode to AllowList in order to have the list of domains you configured for SharingAllowedDomainList to take effect."); } else if (SharingDomainRestrictionMode == SharingDomainRestrictionModes.BlockList) { - WriteWarning("The list of domains in SharingAllowedDomainsList is ignored when you set the SharingDomainRestrictionMode to BlockList. Set the list of blocked domains using the SharingBlockedDomainsList parameter."); + LogWarning("The list of domains in SharingAllowedDomainsList is ignored when you set the SharingDomainRestrictionMode to BlockList. Set the list of blocked domains using the SharingBlockedDomainsList parameter."); } } if (PreventExternalUsersFromResharing.HasValue) @@ -764,18 +764,18 @@ protected override void ExecuteCmdlet() { if (!Tenant.RequireAcceptingAccountMatchInvitedAccount) { - WriteWarning("We automatically enabled RequireAcceptingAccountMatchInvitedAccount because you selected to limit external sharing using domains."); + LogWarning("We automatically enabled RequireAcceptingAccountMatchInvitedAccount because you selected to limit external sharing using domains."); Tenant.RequireAcceptingAccountMatchInvitedAccount = true; } Tenant.SharingBlockedDomainList = SharingBlockedDomainList; modified = true; if ((SharingDomainRestrictionMode == null && Tenant.SharingDomainRestrictionMode != SharingDomainRestrictionModes.BlockList) || SharingDomainRestrictionMode == SharingDomainRestrictionModes.None) { - WriteWarning("You must set SharingDomainRestrictionMode to BlockList in order to have the list of domains you configured for SharingBlockedDomainList to take effect"); + LogWarning("You must set SharingDomainRestrictionMode to BlockList in order to have the list of domains you configured for SharingBlockedDomainList to take effect"); } else if (SharingDomainRestrictionMode == SharingDomainRestrictionModes.AllowList) { - WriteWarning("The list of domains in SharingBlockedDomainsList is ignored when you set the SharingDomainRestrictionMode to AllowList.Set the list of allowed domains using the SharingAllowedDomainsList parameter."); + LogWarning("The list of domains in SharingBlockedDomainsList is ignored when you set the SharingDomainRestrictionMode to AllowList.Set the list of allowed domains using the SharingAllowedDomainsList parameter."); } } if (SharingDomainRestrictionMode.HasValue) @@ -790,7 +790,7 @@ protected override void ExecuteCmdlet() } if (!Tenant.RequireAcceptingAccountMatchInvitedAccount) { - WriteWarning("We automatically enabled RequireAcceptingAccountMatchInvitedAccount because you selected to limit external sharing using domains."); + LogWarning("We automatically enabled RequireAcceptingAccountMatchInvitedAccount because you selected to limit external sharing using domains."); Tenant.RequireAcceptingAccountMatchInvitedAccount = true; } Tenant.SharingDomainRestrictionMode = SharingDomainRestrictionMode.Value; @@ -825,7 +825,7 @@ protected override void ExecuteCmdlet() modified = true; if ((IPAddressEnforcement == null && !Tenant.IPAddressEnforcement) || IPAddressEnforcement == false) { - WriteWarning("The list of IP Addresses you provided will not be enforced until you set IPAddressEnforcement to true"); + LogWarning("The list of IP Addresses you provided will not be enforced until you set IPAddressEnforcement to true"); } } if (IPAddressWACTokenLifetime.HasValue) @@ -856,7 +856,7 @@ protected override void ExecuteCmdlet() { if (DefaultSharingLinkType.Value == SharingLinkType.AnonymousAccess && Tenant.SharingCapability != SharingCapabilities.ExternalUserAndGuestSharing) { - WriteWarning(@"Anonymous access links aren’t enabled for your organization. You must first enable them by running the command ""Set-PnPTenant -SharingCapability ExternalUserAndGuestSharing"" before you can set the DefaultSharingLinkType parameter to AnonymousAccess. We will not set the value in this case."); + LogWarning(@"Anonymous access links aren’t enabled for your organization. You must first enable them by running the command ""Set-PnPTenant -SharingCapability ExternalUserAndGuestSharing"" before you can set the DefaultSharingLinkType parameter to AnonymousAccess. We will not set the value in this case."); } else { @@ -889,7 +889,7 @@ protected override void ExecuteCmdlet() { if (Tenant.SharingCapability != SharingCapabilities.ExternalUserAndGuestSharing) { - WriteWarning(@"Anonymous access links aren’t enabled for your organization. You must first enable them by running the command ""Set-PnPTenant -SharingCapability ExternalUserAndGuestSharing"" before you can set the FileAnonymousLinkType property. We will not set the value in this case."); + LogWarning(@"Anonymous access links aren’t enabled for your organization. You must first enable them by running the command ""Set-PnPTenant -SharingCapability ExternalUserAndGuestSharing"" before you can set the FileAnonymousLinkType property. We will not set the value in this case."); } else { @@ -912,7 +912,7 @@ protected override void ExecuteCmdlet() { if (Tenant.SharingCapability != SharingCapabilities.ExternalUserAndGuestSharing) { - WriteWarning(@"Anonymous access links aren’t enabled for your organization. You must first enable them by running the command ""Set-PnPTenant -SharingCapability ExternalUserAndGuestSharing"" before you can set the FolderAnonymousLinkType property. We will not set the value in this case."); + LogWarning(@"Anonymous access links aren’t enabled for your organization. You must first enable them by running the command ""Set-PnPTenant -SharingCapability ExternalUserAndGuestSharing"" before you can set the FolderAnonymousLinkType property. We will not set the value in this case."); } else { @@ -989,7 +989,7 @@ protected override void ExecuteCmdlet() modified = true; if (!AllowDownloadingNonWebViewableFiles.Value) { - WriteWarning("Users will not be able to download files that can't be viewed on the web. To allow download of files that can't be viewed on the web, run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); + LogWarning("Users will not be able to download files that can't be viewed on the web. To allow download of files that can't be viewed on the web, run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); } } else if (Force || ShouldContinue("To set this parameter, you need to set the Set-PnPTenant -ConditionalAccessPolicy to AllowLimitedAccess. Would you like to set it now?", Properties.Resources.Confirm)) @@ -999,7 +999,7 @@ protected override void ExecuteCmdlet() modified = true; if (!AllowDownloadingNonWebViewableFiles.Value) { - WriteWarning("Users will not be able to download files that can't be viewed on the web. To allow download of files that can't be viewed on the web, run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); + LogWarning("Users will not be able to download files that can't be viewed on the web. To allow download of files that can't be viewed on the web, run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); } } } @@ -1682,7 +1682,7 @@ protected override void ExecuteCmdlet() } if (BlockDownloadFileTypeIds.Contains(SPBlockDownloadFileTypeId.TeamsMeetingRecording)) { - WriteWarning("Please note that this policy only prevents download of Teams Meeting Recording files saved in SharePoint Online by the Teams service. Only new meeting recordings saved after this policy is set will be impacted."); + LogWarning("Please note that this policy only prevents download of Teams Meeting Recording files saved in SharePoint Online by the Teams service. Only new meeting recordings saved after this policy is set will be impacted."); } BlockDownloadFileTypeIds = BlockDownloadFileTypeIds.Distinct().ToArray(); if (ExcludedBlockDownloadGroupIds != null && ExcludedBlockDownloadGroupIds.Length != 0) diff --git a/src/Commands/Admin/SetTenantSite.cs b/src/Commands/Admin/SetTenantSite.cs index 2609719ad..3cb89c009 100644 --- a/src/Commands/Admin/SetTenantSite.cs +++ b/src/Commands/Admin/SetTenantSite.cs @@ -235,7 +235,7 @@ protected override void ExecuteCmdlet() if (LockState.HasValue) { Tenant.SetSiteLockState(Identity.Url, LockState.Value, Wait, Wait ? timeoutFunction : null); - WriteWarning("You changed the lockstate of a site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect."); + LogWarning("You changed the lockstate of a site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect."); } if (!LockState.HasValue) { @@ -330,7 +330,7 @@ private void SetSiteProperties(Func timeoutFunctio Tenant.EnsureProperty(t => t.ShowPeoplePickerSuggestionsForGuestUsers); if (!Tenant.ShowPeoplePickerSuggestionsForGuestUsers) { - WriteWarning("ShowPeoplePickerSuggestionsForGuests users has been disabled for this tenant. See Set-PnPTenant"); + LogWarning("ShowPeoplePickerSuggestionsForGuests users has been disabled for this tenant. See Set-PnPTenant"); } props.ShowPeoplePickerSuggestionsForGuestUsers = ShowPeoplePickerSuggestionsForGuestUsers; updateRequired = true; @@ -379,7 +379,7 @@ private void SetSiteProperties(Func timeoutFunctio updateRequired = true; if (!value) { - WriteWarning("Users will not be able to download files that cannot be viewed on the web. To allow download of files that cannot be viewed on the web run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); + LogWarning("Users will not be able to download files that cannot be viewed on the web. To allow download of files that cannot be viewed on the web run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); } } else @@ -391,7 +391,7 @@ private void SetSiteProperties(Func timeoutFunctio props.AllowDownloadingNonWebViewableFiles = value; if (!value) { - WriteWarning("Users will not be able to download files that cannot be viewed on the web. To allow download of files that cannot be viewed on the web run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); + LogWarning("Users will not be able to download files that cannot be viewed on the web. To allow download of files that cannot be viewed on the web run the cmdlet again and set AllowDownloadingNonWebViewableFiles to true."); } } } @@ -491,7 +491,7 @@ private void SetSiteProperties(Func timeoutFunctio } else { - WriteWarning("Server does not support setting sensitity label"); + LogWarning("Server does not support setting sensitity label"); } if (ParameterSpecified(nameof(LimitedAccessFileType))) diff --git a/src/Commands/Apps/AddApp.cs b/src/Commands/Apps/AddApp.cs index 3a2133c4d..8e967b8da 100644 --- a/src/Commands/Apps/AddApp.cs +++ b/src/Commands/Apps/AddApp.cs @@ -39,19 +39,19 @@ protected override void ExecuteCmdlet() { var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); - WriteVerbose("Checking if the tenant app catalog is a no-script site"); + LogDebug("Checking if the tenant app catalog is a no-script site"); if (ctx.Site.IsNoScriptSite()) { if (Force || ShouldContinue("The tenant appcatalog is a no-script site. Do you want to temporarily enable scripting on it?", Properties.Resources.Confirm)) { - WriteVerbose("Temporarily enabling scripting on the tenant app catalog site"); + LogDebug("Temporarily enabling scripting on the tenant app catalog site"); var tenant = new Tenant(AdminContext); tenant.SetSiteProperties(appcatalogUri.AbsoluteUri, noScriptSite: false); isScriptSettingUpdated = true; } else { - WriteWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); + LogWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); return; } } @@ -91,7 +91,7 @@ protected override void ExecuteCmdlet() { if (isScriptSettingUpdated) { - WriteVerbose("Disabling scripting on the tenant app catalog site"); + LogDebug("Disabling scripting on the tenant app catalog site"); var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); diff --git a/src/Commands/Apps/AddApplicationCustomizer.cs b/src/Commands/Apps/AddApplicationCustomizer.cs index 128b9c3f6..d1025eabc 100644 --- a/src/Commands/Apps/AddApplicationCustomizer.cs +++ b/src/Commands/Apps/AddApplicationCustomizer.cs @@ -58,7 +58,7 @@ protected override void ExecuteCmdlet() break; case CustomActionScope.All: - WriteWarning("CustomActionScope 'All' is not supported for adding CustomActions"); + LogWarning("CustomActionScope 'All' is not supported for adding CustomActions"); break; } } diff --git a/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs b/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs index 218f361d6..176d01da9 100644 --- a/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs +++ b/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs @@ -43,7 +43,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("Service principal not found", nameof(Principal)); } - WriteVerbose($"Adding app role to service principal {principal.DisplayName}"); + LogDebug($"Adding app role to service principal {principal.DisplayName}"); AzureADServicePrincipalAppRole appRole; @@ -67,7 +67,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("AppRole not found", nameof(AppRole)); } - WriteVerbose($"Adding app role {appRole.Value}: {appRole.DisplayName}"); + LogDebug($"Adding app role {appRole.Value}: {appRole.DisplayName}"); var response = ServicePrincipalUtility.AddServicePrincipalRoleAssignment(GraphRequestHelper, principal, appRole); WriteObject(response, false); diff --git a/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs b/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs index 38435f3e6..b856faf63 100644 --- a/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs +++ b/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs @@ -29,7 +29,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("Service principal not found", nameof(Principal)); } - WriteVerbose($"Requesting currently assigned app roles to service principal {principal.DisplayName}"); + LogDebug($"Requesting currently assigned app roles to service principal {principal.DisplayName}"); var appRoleAssignments = ServicePrincipalUtility.GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(GraphRequestHelper, principal.Id); if (ParameterSpecified(nameof(Identity))) diff --git a/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs b/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs index 9f8bf7d6b..62d3387bf 100644 --- a/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs +++ b/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs @@ -28,7 +28,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("Service principal not found", nameof(Principal)); } - WriteVerbose($"Requesting available app roles for service principal {principal.DisplayName}"); + LogDebug($"Requesting available app roles for service principal {principal.DisplayName}"); if (ParameterSpecified(nameof(Identity))) { diff --git a/src/Commands/Apps/GrantAzureADAppSitePermission.cs b/src/Commands/Apps/GrantAzureADAppSitePermission.cs index e2a69f7a0..83510abff 100644 --- a/src/Commands/Apps/GrantAzureADAppSitePermission.cs +++ b/src/Commands/Apps/GrantAzureADAppSitePermission.cs @@ -36,20 +36,20 @@ protected override void ExecuteCmdlet() Guid siteId = Guid.Empty; if (ParameterSpecified(nameof(Site))) { - WriteVerbose($"Using Microsoft Graph to lookup the site Id of the passed in site using -{nameof(Site)}"); + LogDebug($"Using Microsoft Graph to lookup the site Id of the passed in site using -{nameof(Site)}"); siteId = Site.GetSiteIdThroughGraph(Connection, AccessToken); - WriteVerbose($"Site passed in using -{nameof(Site)} resolved to Id {siteId}"); + LogDebug($"Site passed in using -{nameof(Site)} resolved to Id {siteId}"); } else { - WriteVerbose($"No specific site passed in through -{nameof(Site)}, taking the currently connected to site"); + LogDebug($"No specific site passed in through -{nameof(Site)}, taking the currently connected to site"); siteId = new SitePipeBind(Connection.Url).GetSiteIdThroughGraph(Connection, AccessToken); - WriteVerbose($"Currently connected to site has Id {siteId}"); + LogDebug($"Currently connected to site has Id {siteId}"); } if (siteId == Guid.Empty) { - WriteVerbose("Id of the site to provide permissions on could not be defined. Please ensure you're passing in a valid site using -{nameof(Site)}"); + LogDebug("Id of the site to provide permissions on could not be defined. Please ensure you're passing in a valid site using -{nameof(Site)}"); return; } @@ -79,7 +79,7 @@ protected override void ExecuteCmdlet() } }; - WriteVerbose($"Granting App with Id {AppId} the permission{(payload.roles.Length != 1 ? "s" : "")} {string.Join(',', payload.roles)}"); + LogDebug($"Granting App with Id {AppId} the permission{(payload.roles.Length != 1 ? "s" : "")} {string.Join(',', payload.roles)}"); // Make the Graph Grant request var result = Utilities.REST.RestHelper.Post(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions", AccessToken, payload); diff --git a/src/Commands/Apps/PublishApp.cs b/src/Commands/Apps/PublishApp.cs index 08938ca01..9049e1abc 100644 --- a/src/Commands/Apps/PublishApp.cs +++ b/src/Commands/Apps/PublishApp.cs @@ -31,19 +31,19 @@ protected override void ExecuteCmdlet() { var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); - WriteVerbose("Checking if the tenant app catalog is a no-script site"); + LogDebug("Checking if the tenant app catalog is a no-script site"); if (ctx.Site.IsNoScriptSite()) { if (Force || ShouldContinue("The tenant appcatalog is a no-script site. Do you want to temporarily enable scripting on it?", Properties.Resources.Confirm)) { - WriteVerbose("Temporarily enabling scripting on the tenant app catalog site"); + LogDebug("Temporarily enabling scripting on the tenant app catalog site"); var tenant = new Tenant(AdminContext); tenant.SetSiteProperties(appcatalogUri.AbsoluteUri, noScriptSite: false); isScriptSettingUpdated = true; } else { - WriteWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); + LogWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); return; } } @@ -71,7 +71,7 @@ protected override void ExecuteCmdlet() { if (isScriptSettingUpdated) { - WriteVerbose("Disabling scripting on the tenant app catalog site"); + LogDebug("Disabling scripting on the tenant app catalog site"); var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); diff --git a/src/Commands/Apps/RemoveApp.cs b/src/Commands/Apps/RemoveApp.cs index fff7e83f1..e52581278 100644 --- a/src/Commands/Apps/RemoveApp.cs +++ b/src/Commands/Apps/RemoveApp.cs @@ -28,19 +28,19 @@ protected override void ExecuteCmdlet() { var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); - WriteVerbose("Checking if the tenant app catalog is a no-script site"); + LogDebug("Checking if the tenant app catalog is a no-script site"); if (ctx.Site.IsNoScriptSite()) { if (Force || ShouldContinue("The tenant appcatalog is a no-script site. Do you want to temporarily enable scripting on it?", Properties.Resources.Confirm)) { - WriteVerbose("Temporarily enabling scripting on the tenant app catalog site"); + LogDebug("Temporarily enabling scripting on the tenant app catalog site"); var tenant = new Tenant(AdminContext); tenant.SetSiteProperties(appcatalogUri.AbsoluteUri, noScriptSite: false); isScriptSettingUpdated = true; } else { - WriteWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); + LogWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); return; } } @@ -69,7 +69,7 @@ protected override void ExecuteCmdlet() { if (isScriptSettingUpdated) { - WriteVerbose("Disabling scripting on the tenant app catalog site"); + LogDebug("Disabling scripting on the tenant app catalog site"); var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); diff --git a/src/Commands/Apps/RemoveApplicationCustomizer.cs b/src/Commands/Apps/RemoveApplicationCustomizer.cs index 12a5ac498..cb34521dd 100644 --- a/src/Commands/Apps/RemoveApplicationCustomizer.cs +++ b/src/Commands/Apps/RemoveApplicationCustomizer.cs @@ -58,7 +58,7 @@ protected override void ExecuteCmdlet() if (!actions.Any()) { - WriteVerbose($"No application customizers representing the client side extension registration found within the scope '{Scope}'"); + LogDebug($"No application customizers representing the client side extension registration found within the scope '{Scope}'"); return; } diff --git a/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs b/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs index 5085cf8f0..fabd7280c 100644 --- a/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs +++ b/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs @@ -40,7 +40,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("Service principal not found", nameof(Principal)); } - WriteVerbose($"Removing currently assigned app roles from service principal {principal.DisplayName} ({principal.Id})"); + LogDebug($"Removing currently assigned app roles from service principal {principal.DisplayName} ({principal.Id})"); if (ParameterSetName == ParameterSet_BYASSIGNEDAPPROLE) { diff --git a/src/Commands/Apps/SetApplicationCustomizer.cs b/src/Commands/Apps/SetApplicationCustomizer.cs index 8f89e0664..38dbe7032 100644 --- a/src/Commands/Apps/SetApplicationCustomizer.cs +++ b/src/Commands/Apps/SetApplicationCustomizer.cs @@ -70,7 +70,7 @@ protected override void ExecuteCmdlet() if (!actions.Any()) { - WriteVerbose($"No Application Customizers representing the client side extension registration found within the scope '{Scope}'"); + LogDebug($"No Application Customizers representing the client side extension registration found within the scope '{Scope}'"); return; } diff --git a/src/Commands/Apps/UnpublishApp.cs b/src/Commands/Apps/UnpublishApp.cs index dcc59f7ed..290cbcad7 100644 --- a/src/Commands/Apps/UnpublishApp.cs +++ b/src/Commands/Apps/UnpublishApp.cs @@ -28,19 +28,19 @@ protected override void ExecuteCmdlet() { var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); - WriteVerbose("Checking if the tenant app catalog is a no-script site"); + LogDebug("Checking if the tenant app catalog is a no-script site"); if (ctx.Site.IsNoScriptSite()) { if (Force || ShouldContinue("The tenant appcatalog is a no-script site. Do you want to temporarily enable scripting on it?", Properties.Resources.Confirm)) { - WriteVerbose("Temporarily enabling scripting on the tenant app catalog site"); + LogDebug("Temporarily enabling scripting on the tenant app catalog site"); var tenant = new Tenant(AdminContext); tenant.SetSiteProperties(appcatalogUri.AbsoluteUri, noScriptSite: false); isScriptSettingUpdated = true; } else { - WriteWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); + LogWarning("Scripting is disabled on the tenant app catalog site. This command cannot proceed without allowing scripts."); return; } } @@ -68,7 +68,7 @@ protected override void ExecuteCmdlet() { if (isScriptSettingUpdated) { - WriteVerbose("Disabling scripting on the tenant app catalog site"); + LogDebug("Disabling scripting on the tenant app catalog site"); var appcatalogUri = ClientContext.Web.GetAppCatalog(); var ctx = ClientContext.Clone(appcatalogUri); diff --git a/src/Commands/AzureAD/GetAzureADAppPermission.cs b/src/Commands/AzureAD/GetAzureADAppPermission.cs index ab98c621e..79c3703ec 100644 --- a/src/Commands/AzureAD/GetAzureADAppPermission.cs +++ b/src/Commands/AzureAD/GetAzureADAppPermission.cs @@ -23,7 +23,7 @@ protected override void ExecuteCmdlet() var app = Identity.GetApp(GraphRequestHelper); if (app == null) { - WriteError(new PSArgumentException("Azure AD App not found"), ErrorCategory.ObjectNotFound); + LogError(new PSArgumentException("Azure AD App not found")); } WriteObject(ConvertToPSObject(app)); } diff --git a/src/Commands/AzureAD/RegisterAzureADApp.cs b/src/Commands/AzureAD/RegisterAzureADApp.cs index 9e01e3480..5e50b1e6c 100644 --- a/src/Commands/AzureAD/RegisterAzureADApp.cs +++ b/src/Commands/AzureAD/RegisterAzureADApp.cs @@ -189,7 +189,7 @@ protected override void ProcessRecord() } if (!scopes.Any()) { - messageWriter.WriteWarning("No permissions specified, using default permissions"); + messageWriter.LogWarning("No permissions specified, using default permissions"); scopes.Add(permissionScopes.GetScope(PermissionScopes.ResourceAppId_SPO, "Sites.FullControl.All", "Role")); // AppOnly scopes.Add(permissionScopes.GetScope(PermissionScopes.ResourceAppId_SPO, "AllSites.FullControl", "Scope")); // AppOnly scopes.Add(permissionScopes.GetScope(PermissionScopes.ResourceAppId_Graph, "Group.ReadWrite.All", "Role")); // AppOnly @@ -429,7 +429,7 @@ private string GetAuthToken(CmdletMessageWriter messageWriter) token = AzureAuthHelper.AuthenticateDeviceLogin(cancellationTokenSource, messageWriter, AzureEnvironment, MicrosoftGraphEndPoint); if (token == null) { - messageWriter.WriteWarning("Operation cancelled or no token retrieved."); + messageWriter.LogWarning("Operation cancelled or no token retrieved."); } messageWriter.Stop(); }); @@ -442,7 +442,7 @@ private string GetAuthToken(CmdletMessageWriter messageWriter) token = AzureAuthHelper.AuthenticateInteractive(cancellationTokenSource, messageWriter, AzureEnvironment, Tenant, MicrosoftGraphEndPoint); if (token == null) { - messageWriter.WriteWarning("Operation cancelled or no token retrieved."); + messageWriter.LogWarning("Operation cancelled or no token retrieved."); } messageWriter.Stop(); }); @@ -666,7 +666,7 @@ private void StartConsentFlow(string loginEndPoint, AzureADApp azureApp, string using (var authManager = AuthenticationManager.CreateWithDeviceLogin(azureApp.AppId, Tenant, (deviceCodeResult) => { ClipboardService.SetText(deviceCodeResult.UserCode); - messageWriter.WriteWarning($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard and a new tab in the browser has been opened. Please paste this code in there and proceed.\n\n"); + messageWriter.LogWarning($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard and a new tab in the browser has been opened. Please paste this code in there and proceed.\n\n"); BrowserHelper.OpenBrowserForInteractiveLogin(deviceCodeResult.VerificationUrl, BrowserHelper.FindFreeLocalhostRedirectUri(), cancellationTokenSource); return Task.FromResult(0); }, AzureEnvironment)) @@ -703,7 +703,7 @@ private void SetLogo(AzureADApp azureApp, string token) { try { - WriteVerbose("Setting the logo for the EntraID app"); + LogDebug("Setting the logo for the EntraID app"); var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}"; if (AzureEnvironment == AzureEnvironment.Custom) @@ -745,7 +745,7 @@ private void SetLogo(AzureADApp azureApp, string token) var requestHelper = new ApiRequestHelper(GetType(), PnPConnection.Current); requestHelper.Put2(endpoint, byteArrayContent, token); - WriteVerbose("Successfully set the logo for the Entra ID app"); + LogDebug("Successfully set the logo for the Entra ID app"); } else { @@ -754,12 +754,12 @@ private void SetLogo(AzureADApp azureApp, string token) } catch (Exception ex) { - WriteWarning("Something went wrong setting the logo " + ex.Message); + LogWarning("Something went wrong setting the logo " + ex.Message); } } else { - WriteWarning("Logo File does not exist, ignoring setting the logo"); + LogWarning("Logo File does not exist, ignoring setting the logo"); } } } diff --git a/src/Commands/AzureAD/RegisterEntraIDAppForInteractiveLogin.cs b/src/Commands/AzureAD/RegisterEntraIDAppForInteractiveLogin.cs index 86ea26416..30630c75d 100644 --- a/src/Commands/AzureAD/RegisterEntraIDAppForInteractiveLogin.cs +++ b/src/Commands/AzureAD/RegisterEntraIDAppForInteractiveLogin.cs @@ -127,7 +127,7 @@ protected override void ProcessRecord() } if (!scopes.Any()) { - messageWriter.WriteWarning("No permissions specified, using default permissions"); + messageWriter.LogWarning("No permissions specified, using default permissions"); scopes.Add(permissionScopes.GetScope(PermissionScopes.ResourceAppId_SPO, "TermStore.ReadWrite.All", "Scope")); // Delegate scopes.Add(permissionScopes.GetScope(PermissionScopes.ResourceAppId_SPO, "AllSites.FullControl", "Scope")); // Delegate scopes.Add(permissionScopes.GetScope(PermissionScopes.ResourceAppId_Graph, "Group.ReadWrite.All", "Scope")); // Delegate @@ -356,7 +356,7 @@ private string GetAuthToken(CmdletMessageWriter messageWriter) token = AzureAuthHelper.AuthenticateDeviceLogin(cancellationTokenSource, messageWriter, AzureEnvironment, MicrosoftGraphEndPoint); if (token == null) { - messageWriter.WriteWarning("Operation cancelled or no token retrieved."); + messageWriter.LogWarning("Operation cancelled or no token retrieved."); } messageWriter.Stop(); }); @@ -369,7 +369,7 @@ private string GetAuthToken(CmdletMessageWriter messageWriter) token = AzureAuthHelper.AuthenticateInteractive(cancellationTokenSource, messageWriter, AzureEnvironment, Tenant, MicrosoftGraphEndPoint); if (token == null) { - messageWriter.WriteWarning("Operation cancelled or no token retrieved."); + messageWriter.LogWarning("Operation cancelled or no token retrieved."); } messageWriter.Stop(); }); @@ -507,7 +507,7 @@ private void StartConsentFlow(string loginEndPoint, AzureADApp azureApp, string using (var authManager = AuthenticationManager.CreateWithDeviceLogin(azureApp.AppId, Tenant, (deviceCodeResult) => { ClipboardService.SetText(deviceCodeResult.UserCode); - messageWriter.WriteWarning($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard and a new tab in the browser has been opened. Please paste this code in there and proceed.\n\n"); + messageWriter.LogWarning($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard and a new tab in the browser has been opened. Please paste this code in there and proceed.\n\n"); BrowserHelper.OpenBrowserForInteractiveLogin(deviceCodeResult.VerificationUrl, BrowserHelper.FindFreeLocalhostRedirectUri(), cancellationTokenSource); return Task.FromResult(0); }, AzureEnvironment)) @@ -564,7 +564,7 @@ private void SetLogo(AzureADApp azureApp, string token) { try { - WriteVerbose("Setting the logo for the EntraID app"); + LogDebug("Setting the logo for the EntraID app"); var graphEndpoint = $"https://{AuthenticationManager.GetGraphEndPoint(AzureEnvironment)}"; if (AzureEnvironment == AzureEnvironment.Custom) @@ -606,7 +606,7 @@ private void SetLogo(AzureADApp azureApp, string token) var requestHelper = new ApiRequestHelper(GetType(), PnPConnection.Current); requestHelper.Put2(endpoint, byteArrayContent, token); - WriteVerbose("Successfully set the logo for the Entra ID app"); + LogDebug("Successfully set the logo for the Entra ID app"); } else { @@ -615,12 +615,12 @@ private void SetLogo(AzureADApp azureApp, string token) } catch (Exception ex) { - WriteWarning("Something went wrong setting the logo " + ex.Message); + LogWarning("Something went wrong setting the logo " + ex.Message); } } else { - WriteWarning("Logo File does not exist, ignoring setting the logo"); + LogWarning("Logo File does not exist, ignoring setting the logo"); } } } diff --git a/src/Commands/AzureAD/RegisterManagementShellAccess.cs b/src/Commands/AzureAD/RegisterManagementShellAccess.cs index 63a8edcba..8b80a9b6a 100644 --- a/src/Commands/AzureAD/RegisterManagementShellAccess.cs +++ b/src/Commands/AzureAD/RegisterManagementShellAccess.cs @@ -1,4 +1,5 @@ using PnP.Framework; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Utilities; using System; using System.Management.Automation; @@ -6,7 +7,7 @@ namespace PnP.PowerShell.Commands.AzureAD { [Cmdlet(VerbsLifecycle.Register, "PnPManagementShellAccess")] - public class RegisterManagementShellAccess : PSCmdlet + public class RegisterManagementShellAccess : BasePSCmdlet { private const string ParameterSet_REGISTER = "Register access"; private const string ParameterSet_SHOWURL = "Show Consent Url"; diff --git a/src/Commands/AzureAD/RemoveAzureADUser.cs b/src/Commands/AzureAD/RemoveAzureADUser.cs index 8ae443104..d44cbe02e 100644 --- a/src/Commands/AzureAD/RemoveAzureADUser.cs +++ b/src/Commands/AzureAD/RemoveAzureADUser.cs @@ -19,28 +19,28 @@ public class RemoveAzureADUser : PnPGraphCmdlet protected override void ExecuteCmdlet() { - WriteVerbose($"Looking up user provided through the {nameof(Identity)} parameter"); + LogDebug($"Looking up user provided through the {nameof(Identity)} parameter"); User user = Identity.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) { - WriteWarning($"User provided through the {nameof(Identity)} parameter could not be found"); + LogWarning($"User provided through the {nameof(Identity)} parameter could not be found"); return; } if (WhatIf.ToBool()) { - WriteVerbose($"Would delete user with Id {user.Id} if {nameof(WhatIf)} was not present"); + LogDebug($"Would delete user with Id {user.Id} if {nameof(WhatIf)} was not present"); return; } - WriteVerbose($"Deleting user with Id {user.Id}"); + LogDebug($"Deleting user with Id {user.Id}"); var graphResult = GraphRequestHelper.Delete($"v1.0/users/{user.Id}"); if (graphResult.StatusCode == System.Net.HttpStatusCode.NoContent) { - WriteVerbose("User deleted successfully"); + LogDebug("User deleted successfully"); } else { diff --git a/src/Commands/AzureAD/SetAzureADGroup.cs b/src/Commands/AzureAD/SetAzureADGroup.cs index 04682ebc3..42d2ae498 100644 --- a/src/Commands/AzureAD/SetAzureADGroup.cs +++ b/src/Commands/AzureAD/SetAzureADGroup.cs @@ -98,12 +98,12 @@ protected override void ExecuteCmdlet() catch (Exception e) { while (e.InnerException != null) e = e.InnerException; - WriteError(new ErrorRecord(e, "GROUPUPDATEFAILED", ErrorCategory.InvalidOperation, this)); + LogError(e); } } else { - WriteError(new ErrorRecord(new Exception("Group not found"), "GROUPNOTFOUND", ErrorCategory.ObjectNotFound, this)); + LogError("Group not found"); } } } diff --git a/src/Commands/Base/AddStoredCredential.cs b/src/Commands/Base/AddStoredCredential.cs index f6eded7cb..f69ad7e7a 100644 --- a/src/Commands/Base/AddStoredCredential.cs +++ b/src/Commands/Base/AddStoredCredential.cs @@ -5,7 +5,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Add, "PnPStoredCredential")] [OutputType(typeof(void))] - public class AddStoredCredential : PSCmdlet + public class AddStoredCredential : BasePSCmdlet { [Parameter(Mandatory = true)] public string Name; diff --git a/src/Commands/Base/BasePSCmdlet.cs b/src/Commands/Base/BasePSCmdlet.cs index e8e54c130..0a2aa9841 100644 --- a/src/Commands/Base/BasePSCmdlet.cs +++ b/src/Commands/Base/BasePSCmdlet.cs @@ -9,53 +9,79 @@ namespace PnP.PowerShell.Commands.Base /// public class BasePSCmdlet : PSCmdlet { + /// + /// Generate a new correlation id for each cmdlet execution. This is used to correlate log entries in the PnP PowerShell log stream. + /// + public virtual Guid? CorrelationId { get; protected set; } = Guid.NewGuid(); + + #region Cmdlet execution + + /// + /// Triggered when the cmdlet is started. This is the place to do any initialization work. + /// protected override void BeginProcessing() { - Framework.Diagnostics.Log.Debug("PnPPowerShell", $"Executing {MyInvocation.MyCommand.Name}"); + LogDebug($"Cmdlet execution started for {MyInvocation.Line}"); base.BeginProcessing(); - PnP.Framework.Diagnostics.Log.Info("PnP.PowerShell", $"Executing {this.MyInvocation.InvocationName}"); - if (MyInvocation.MyCommand.Name.ToLower() != MyInvocation.InvocationName.ToLower()) + + CheckForDeprecationAttributes(); + } + + /// + /// Executes the cmdlet. This is the place to do the actual work of the cmdlet. + /// + protected virtual void ExecuteCmdlet() + { } + + /// + /// Triggered for the execution of the cmdlet. Use ExecuteCmdlet() to do the actual work of the cmdlet. + /// + protected override void ProcessRecord() + { + try { - var attribute = Attribute.GetCustomAttribute(this.GetType(), typeof(WriteAliasWarningAttribute)); - if (attribute != null) + ExecuteCmdlet(); + } + catch (Model.Graph.GraphException gex) + { + var errorMessage = gex.Error.Message; + + if (gex.Error.Code == "Authorization_RequestDenied") { - var warningAttribute = attribute as WriteAliasWarningAttribute; - if (!string.IsNullOrEmpty(warningAttribute?.DeprecationMessage)) + if (!string.IsNullOrEmpty(gex.AccessToken)) { - WriteWarning(warningAttribute.DeprecationMessage); + TokenHandler.EnsureRequiredPermissionsAvailableInAccessTokenAudience(GetType(), gex.AccessToken); } } + if (string.IsNullOrWhiteSpace(errorMessage) && gex.HttpResponse != null && gex.HttpResponse.StatusCode == System.Net.HttpStatusCode.Forbidden) + { + errorMessage = "Access denied. Check for the required permissions."; + } + throw new PSInvalidOperationException(errorMessage); } - // if (PnPConnection.Current == null) - // { - // if (Settings.Current.LastUserTenant != null) - // { - // var clientid = PnPConnection.GetCacheClientId(Settings.Current.LastUserTenant); - // if (clientid != null) - // { - // var cancellationTokenSource = new CancellationTokenSource(); - // PnPConnection.Current = PnPConnection.CreateWithInteractiveLogin(new Uri(Settings.Current.LastUserTenant.ToLower()), clientid, null, Framework.AzureEnvironment.Production, cancellationTokenSource, false, null, false, false, Host); - // } - - // } - // } } + /// + /// Triggered when the cmdlet is done executing. This is the place to do any cleanup or finalization work. + /// protected override void EndProcessing() { base.EndProcessing(); + LogDebug($"Cmdlet execution done for {MyInvocation.Line}"); } /// - /// Checks if a parameter with the provided name has been provided in the execution command + /// Triggered when the cmdlet is stopped /// - /// Name of the parameter to validate if it has been provided in the execution command - /// True if a parameter with the provided name is present, false if it is not - public bool ParameterSpecified(string parameterName) + protected override void StopProcessing() { - return MyInvocation.BoundParameters.ContainsKey(parameterName); + base.StopProcessing(); } + #endregion + + #region Helper methods + protected string ErrorActionSetting { get @@ -67,42 +93,84 @@ protected string ErrorActionSetting } } - protected virtual void ExecuteCmdlet() - { } - - protected override void ProcessRecord() + /// + /// Checks if deprecation attribute is present on the cmdlet and if so, writes a warning message to the console to notify the user to change their script to use the new cmdlet name. + /// + private void CheckForDeprecationAttributes() { - try + if (!MyInvocation.MyCommand.Name.Equals(MyInvocation.InvocationName, StringComparison.CurrentCultureIgnoreCase)) { - ExecuteCmdlet(); - } - catch (Model.Graph.GraphException gex) - { - var errorMessage = gex.Error.Message; - - if (gex.Error.Code == "Authorization_RequestDenied") + var attribute = Attribute.GetCustomAttribute(GetType(), typeof(WriteAliasWarningAttribute)); + if (attribute != null) { - if (!string.IsNullOrEmpty(gex.AccessToken)) + var warningAttribute = attribute as WriteAliasWarningAttribute; + if (!string.IsNullOrEmpty(warningAttribute?.DeprecationMessage)) { - TokenHandler.EnsureRequiredPermissionsAvailableInAccessTokenAudience(GetType(), gex.AccessToken); + LogWarning(warningAttribute.DeprecationMessage); } } - if (string.IsNullOrWhiteSpace(errorMessage) && gex.HttpResponse != null && gex.HttpResponse.StatusCode == System.Net.HttpStatusCode.Forbidden) - { - errorMessage = "Access denied. Check for the required permissions."; - } - throw new PSInvalidOperationException(errorMessage); } } - protected override void StopProcessing() + /// + /// Checks if a parameter with the provided name has been provided in the execution command + /// + /// Name of the parameter to validate if it has been provided in the execution command + /// True if a parameter with the provided name is present, false if it is not + public bool ParameterSpecified(string parameterName) { - base.StopProcessing(); + return MyInvocation.BoundParameters.ContainsKey(parameterName); + } + + #endregion + + #region Logging + + /// + /// Allows logging an error + /// + /// The exception to log as an error + internal void LogError(Exception exception) + { + LogError(exception.Message); + } + + /// + /// Allows logging an error + /// + /// The message to log + internal void LogError(string message) + { + Utilities.Logging.LoggingUtility.Error(this, message, correlationId: CorrelationId); } - internal void WriteError(Exception exception, ErrorCategory errorCategory, object target = null) + /// + /// Allows logging a debug message + /// + /// The message to log + internal void LogDebug(string message) + { + Utilities.Logging.LoggingUtility.Debug(this, message, correlationId: CorrelationId); + } + + /// + /// Allows logging a warning + /// + /// The message to log + internal void LogWarning(string message) + { + Utilities.Logging.LoggingUtility.Warning(this, message, correlationId: CorrelationId); + } + + /// + /// Allows logging an informational message + /// + /// The message to log + internal void LogInformational(string message) { - WriteError(new ErrorRecord(exception, string.Empty, errorCategory, target)); + Utilities.Logging.LoggingUtility.Info(this, message, correlationId: CorrelationId); } + + #endregion } } diff --git a/src/Commands/Base/ClearTraceLog.cs b/src/Commands/Base/ClearTraceLog.cs new file mode 100644 index 000000000..d5c95e606 --- /dev/null +++ b/src/Commands/Base/ClearTraceLog.cs @@ -0,0 +1,24 @@ +using System.Diagnostics; +using System.Management.Automation; +using PnP.PowerShell.Commands.Utilities.Logging; + +namespace PnP.PowerShell.Commands.Base +{ + [Cmdlet(VerbsCommon.Clear, "PnPTraceLog")] + [OutputType(typeof(void))] + public class ClearTraceLog : BasePSCmdlet + { + protected override void ProcessRecord() + { + if (Trace.Listeners[LogStreamListener.DefaultListenerName] is not LogStreamListener logStreamListener) + { + LogWarning($"Log stream listener named {LogStreamListener.DefaultListenerName} not found. No entries cleared."); + } + else + { + LogDebug($"Clearing {(logStreamListener.Entries.Count != 1 ? $"{logStreamListener.Entries.Count} log entries" : "one log entry")} from log stream listener named {LogStreamListener.DefaultListenerName}"); + logStreamListener.Entries.Clear(); + } + } + } +} \ No newline at end of file diff --git a/src/Commands/Base/ConnectOnline.cs b/src/Commands/Base/ConnectOnline.cs index f2506ae59..f50000d75 100644 --- a/src/Commands/Base/ConnectOnline.cs +++ b/src/Commands/Base/ConnectOnline.cs @@ -297,7 +297,7 @@ protected override void ProcessRecord() /// protected void Connect(ref CancellationToken cancellationToken) { - WriteVerbose($"PnP PowerShell Cmdlets ({new SemanticVersion(Assembly.GetExecutingAssembly().GetName().Version)})"); + LogDebug($"PnP PowerShell Cmdlets ({new SemanticVersion(Assembly.GetExecutingAssembly().GetName().Version)})"); if (!string.IsNullOrEmpty(Url)) { @@ -328,7 +328,7 @@ protected void Connect(ref CancellationToken cancellationToken) if (ParameterSpecified(nameof(Connection))) { // Reuse some parameters of the passed in connection - WriteVerbose("Reusing some of the connection parameters from passed in connection"); + LogDebug("Reusing some of the connection parameters from passed in connection"); ClientId = Connection.ClientId; } @@ -386,7 +386,7 @@ protected void Connect(ref CancellationToken cancellationToken) } // Connection has been established - WriteVerbose($"Connected"); + LogDebug($"Connected"); if (newConnection.Url != null) { @@ -407,12 +407,12 @@ protected void Connect(ref CancellationToken cancellationToken) try { newConnection.Context.ExecuteQueryRetry(); - WriteVerbose($"Site at {Url} exists"); + LogInformational($"Site at {Url} exists"); } catch (System.Net.WebException e) when (e.Message.Contains("404")) { - WriteVerbose($"Site at {Url} does not exist"); - throw new PSInvalidOperationException($"The specified site {Url} does not exist", e); + LogError($"Site at {Url} does not exist"); + //throw new PSInvalidOperationException($"The specified site {Url} does not exist", e); } catch (TargetInvocationException tex) { @@ -470,7 +470,7 @@ protected void Connect(ref CancellationToken cancellationToken) /// PnPConnection based on the parameters provided in the parameter set private PnPConnection ConnectACSAppOnly() { - WriteVerbose("Connecting using the SharePoint Online Access Control Services(ACS) App-Only"); + LogDebug("Connecting using the SharePoint Online Access Control Services(ACS) App-Only"); CmdletMessageWriter.WriteFormattedMessage(this, new CmdletMessageWriter.Message { Text = "Connecting with Client Secret uses legacy authentication and provides limited functionality. We can for instance not execute requests towards the Microsoft Graph, which limits cmdlets related to Microsoft Teams, Microsoft Planner, Microsoft Flow and Microsoft 365 Groups. You can hide this warning by using Connect-PnPOnline [your parameters] -WarningAction Ignore", Formatted = true, Type = CmdletMessageWriter.MessageType.Warning }); if (Connection?.ClientId == ClientId && @@ -485,10 +485,10 @@ private PnPConnection ConnectACSAppOnly() ClientId = GetAppId(); if (ClientId != null) { - WriteVerbose("Using Managed AppId from secure store"); + LogDebug("Using Managed AppId from secure store"); } } - WriteVerbose($"Using ClientID {ClientId}"); + LogDebug($"Using ClientID {ClientId}"); return PnPConnection.CreateWithACSAppOnly(new Uri(Url), Realm, ClientId, ClientSecret, TenantAdminUrl, AzureEnvironment); } @@ -500,7 +500,7 @@ private PnPConnection ConnectACSAppOnly() /// PnPConnection based on the parameters provided in the parameter set private PnPConnection ConnectDeviceLogin() { - WriteVerbose("Connecting using Device Login"); + LogDebug("Connecting using Device Login"); var messageWriter = new CmdletMessageWriter(this); PnPConnection connection = null; @@ -549,7 +549,7 @@ private PnPConnection ConnectDeviceLogin() } else { - messageWriter.WriteVerbose("Using Managed AppId from secure store"); + messageWriter.LogDebug("Using Managed AppId from secure store"); } } @@ -559,7 +559,7 @@ private PnPConnection ConnectDeviceLogin() } catch (Exception ex) { - messageWriter.WriteWarning(ex.Message, false); + messageWriter.LogWarning(ex.Message, false); messageWriter.Finished = true; } }, cancellationTokenSource.Token); @@ -573,8 +573,8 @@ private PnPConnection ConnectDeviceLogin() /// PnPConnection based on the parameters provided in the parameter set private PnPConnection ConnectAppOnlyWithCertificate() { - WriteVerbose("Connecting using Entra ID App-Only using a certificate"); - WriteVerbose($"Using ClientID {ClientId}"); + LogDebug("Connecting using Entra ID App-Only using a certificate"); + LogDebug($"Using ClientID {ClientId}"); if (ParameterSpecified(nameof(CertificatePath))) { @@ -659,7 +659,7 @@ private PnPConnection ConnectAppOnlyWithCertificate() /// PnPConnection based on the parameters provided in the parameter set private PnPConnection ConnectAccessToken() { - WriteVerbose("Connecting using a provided Access Token"); + LogDebug("Connecting using a provided Access Token"); return PnPConnection.CreateWithAccessToken(!string.IsNullOrEmpty(Url) ? new Uri(Url) : null, AccessToken, TenantAdminUrl); } @@ -670,7 +670,7 @@ private PnPConnection ConnectAccessToken() /// PnPConnection based on credentials authentication private PnPConnection ConnectCredentials(PSCredential credentials, InitializationType initializationType = InitializationType.Credentials) { - WriteVerbose("Connecting using username and password"); + LogDebug("Connecting using username and password"); if (!CurrentCredentials && credentials == null) { @@ -705,7 +705,7 @@ private PnPConnection ConnectCredentials(PSCredential credentials, Initializatio } else { - WriteVerbose("Using Managed AppId from secure store"); + LogDebug("Using Managed AppId from secure store"); } } @@ -717,7 +717,7 @@ private PnPConnection ConnectCredentials(PSCredential credentials, Initializatio ReuseAuthenticationManager(); } } - WriteVerbose($"Using ClientID {ClientId}"); + LogDebug($"Using ClientID {ClientId}"); return PnPConnection.CreateWithCredentials(this, new Uri(Url), credentials, CurrentCredentials, @@ -732,15 +732,15 @@ private PnPConnection ConnectCredentials(PSCredential credentials, Initializatio private PnPConnection ConnectManagedIdentity() { - WriteVerbose("Connecting using an Azure Managed Identity"); + LogDebug("Connecting using an Azure Managed Identity"); - WriteVerbose($"ClientID: {UserAssignedManagedIdentityClientId}"); + LogDebug($"ClientID: {UserAssignedManagedIdentityClientId}"); return PnPConnection.CreateWithManagedIdentity(Url, TenantAdminUrl, UserAssignedManagedIdentityObjectId, UserAssignedManagedIdentityClientId, UserAssignedManagedIdentityAzureResourceId); } private PnPConnection ConnectInteractive() { - WriteVerbose("Connecting using Interactive login"); + LogDebug("Connecting using Interactive login"); if (ClientId == null) { @@ -760,7 +760,7 @@ private PnPConnection ConnectInteractive() } else { - WriteVerbose("Using Managed AppId from secure store"); + LogDebug("Using Managed AppId from secure store"); } } if (Connection?.ClientId == ClientId && Connection?.ConnectionMethod == ConnectionMethod.Credentials) @@ -770,13 +770,13 @@ private PnPConnection ConnectInteractive() ReuseAuthenticationManager(); } } - WriteVerbose($"Using ClientID {ClientId}"); + LogDebug($"Using ClientID {ClientId}"); return PnPConnection.CreateWithInteractiveLogin(new Uri(Url.ToLower()), ClientId, TenantAdminUrl, AzureEnvironment, cancellationTokenSource, ForceAuthentication, Tenant, false, PersistLogin, Host); } private PnPConnection ConnectEnvironmentVariable(InitializationType initializationType = InitializationType.EnvironmentVariable) { - WriteVerbose("Connecting using information from environment variables"); + LogDebug("Connecting using information from environment variables"); string username = Environment.GetEnvironmentVariable("AZURE_USERNAME") ?? Environment.GetEnvironmentVariable("ENTRAID_USERNAME"); string password = Environment.GetEnvironmentVariable("AZURE_PASSWORD") ?? Environment.GetEnvironmentVariable("ENTRAID_PASSWORD"); @@ -789,7 +789,7 @@ private PnPConnection ConnectEnvironmentVariable(InitializationType initializati azureClientId = GetAppId(); if (azureClientId != null) { - WriteVerbose("Using Managed AppId from secure store"); + LogDebug("Using Managed AppId from secure store"); } } @@ -833,7 +833,7 @@ private PnPConnection ConnectEnvironmentVariable(InitializationType initializati ReuseAuthenticationManager(); } - WriteVerbose($"ClientID: {azureClientId}"); + LogDebug($"ClientID: {azureClientId}"); return PnPConnection.CreateWithCert(new Uri(Url), azureClientId, Tenant, TenantAdminUrl, AzureEnvironment, certificate, true); } @@ -857,7 +857,7 @@ private PnPConnection ConnectEnvironmentVariable(InitializationType initializati ReuseAuthenticationManager(); } } - WriteVerbose($"ClientID: {azureClientId}"); + LogDebug($"ClientID: {azureClientId}"); return PnPConnection.CreateWithCredentials(this, new Uri(Url), credentials, @@ -875,14 +875,14 @@ private PnPConnection ConnectEnvironmentVariable(InitializationType initializati private PnPConnection ConnectAzureADWorkloadIdentity() { - WriteVerbose("Connecting using Entra ID Workload Identity"); + LogDebug("Connecting using Entra ID Workload Identity"); return PnPConnection.CreateWithAzureADWorkloadIdentity(Url, TenantAdminUrl); } private PnPConnection ConnectWithOSLogin() { - WriteVerbose("Connecting using Web Account Manager (WAM)"); + LogDebug("Connecting using Web Account Manager (WAM)"); if (ClientId == null) { @@ -897,7 +897,7 @@ private PnPConnection ConnectWithOSLogin() } else { - WriteVerbose("Using Managed AppId from secure store"); + LogDebug("Using Managed AppId from secure store"); } } if (Connection?.ClientId == ClientId && Connection?.ConnectionMethod == ConnectionMethod.Credentials) @@ -908,7 +908,7 @@ private PnPConnection ConnectWithOSLogin() } } - WriteVerbose($"Using ClientID {ClientId}"); + LogDebug($"Using ClientID {ClientId}"); if (PnPConnection.CacheEnabled(Url, ClientId)) { WriteObject("Cache used. Clear the cache entry with Disconnect-PnPOnline"); diff --git a/src/Commands/Base/DisconnectOnline.cs b/src/Commands/Base/DisconnectOnline.cs index 6d69b62a7..0bd2cce7c 100644 --- a/src/Commands/Base/DisconnectOnline.cs +++ b/src/Commands/Base/DisconnectOnline.cs @@ -9,7 +9,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommunications.Disconnect, "PnPOnline")] [OutputType(typeof(void))] - public class DisconnectOnline : PSCmdlet + public class DisconnectOnline : BasePSCmdlet { [Parameter(Mandatory = false)] diff --git a/src/Commands/Base/FormatTraceLog.cs b/src/Commands/Base/FormatTraceLog.cs index 0bdee2dfd..caaf529d0 100644 --- a/src/Commands/Base/FormatTraceLog.cs +++ b/src/Commands/Base/FormatTraceLog.cs @@ -1,12 +1,12 @@ using System.Management.Automation; -using PnP.PowerShell.Model; +using PnP.PowerShell.Commands.Utilities.Logging; namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Format, "PnPTraceLog")] - public class FormatTraceLog : PSCmdlet + public class FormatTraceLog : BasePSCmdlet { - [Parameter(Mandatory = false, Position = 0, ValueFromPipeline = true, ParameterSetName = "On")] + [Parameter(Mandatory = false, Position = 0, ValueFromPipeline = true)] public string LogLine; protected override void ProcessRecord() diff --git a/src/Commands/Base/GetAccessToken.cs b/src/Commands/Base/GetAccessToken.cs index 83a203458..1c7fd2150 100644 --- a/src/Commands/Base/GetAccessToken.cs +++ b/src/Commands/Base/GetAccessToken.cs @@ -84,7 +84,7 @@ protected override void ExecuteCmdlet() if (accessTokenValue == null) { - WriteError(new PSArgumentException("Unable to retrieve access token"), ErrorCategory.InvalidResult); + LogError(new PSArgumentException("Unable to retrieve access token")); } if (ListPermissionScopes.IsPresent) { diff --git a/src/Commands/Base/GetAzureCertificate.cs b/src/Commands/Base/GetAzureCertificate.cs index 19fd4b3b3..1a07d490e 100644 --- a/src/Commands/Base/GetAzureCertificate.cs +++ b/src/Commands/Base/GetAzureCertificate.cs @@ -10,7 +10,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Get, "PnPAzureCertificate", DefaultParameterSetName = "SELF")] [OutputType(typeof(Model.AzureCertificate))] - public class GetPnPAdalCertificate : PSCmdlet + public class GetPnPAzureCertificate : BasePSCmdlet { [Parameter(Mandatory = true)] [Alias("CertificatePath")] @@ -58,7 +58,7 @@ static string GetManifestEntry(X509Certificate2 certificate) return manifestEntry; } - static string/*?*/ GetPfxBase64OrWarn(Cmdlet cmdlet, X509Certificate2 certificate, SecureString password) + static string/*?*/ GetPfxBase64OrWarn(BasePSCmdlet cmdlet, X509Certificate2 certificate, SecureString password) { try { @@ -68,12 +68,12 @@ static string GetManifestEntry(X509Certificate2 certificate) } catch (Exception ex) { - cmdlet.WriteWarning(ex.Message); + cmdlet.LogWarning(ex.Message); return null; } } - internal static void WriteAzureCertificateOutput(PSCmdlet cmdlet, X509Certificate2 certificate, SecureString password) + internal static void WriteAzureCertificateOutput(BasePSCmdlet cmdlet, X509Certificate2 certificate, SecureString password) { string manifestEntry = GetManifestEntry(certificate); var pfxBase64 = GetPfxBase64OrWarn(cmdlet, certificate, password); diff --git a/src/Commands/Base/GetChangeLog.cs b/src/Commands/Base/GetChangeLog.cs index 03c78044c..add080245 100644 --- a/src/Commands/Base/GetChangeLog.cs +++ b/src/Commands/Base/GetChangeLog.cs @@ -1,12 +1,13 @@ using System.Management.Automation; using System.Net.Http; using System.Text.RegularExpressions; +using PnP.PowerShell.Commands.Base; namespace PnP.PowerShell.Commands { [Cmdlet(VerbsCommon.Get, "PnPChangeLog", DefaultParameterSetName = ParameterSet_SpecificVersion)] [OutputType(typeof(string))] - public partial class GetChangeLog : PSCmdlet + public partial class GetChangeLog : BasePSCmdlet { private const string ParameterSet_Nightly = "Current nightly"; private const string ParameterSet_SpecificVersion = "Specific version"; @@ -49,7 +50,7 @@ private string RetrieveLatestStableRelease(HttpClient httpClient) { var url = "https://raw.githubusercontent.com/pnp/powershell/dev/CHANGELOG.md"; - WriteVerbose($"Retrieving changelog from {url}"); + LogDebug($"Retrieving changelog from {url}"); var response = httpClient.GetAsync(url).GetAwaiter().GetResult(); if (!response.IsSuccessStatusCode) @@ -57,7 +58,7 @@ private string RetrieveLatestStableRelease(HttpClient httpClient) throw new PSInvalidOperationException("Failed to retrieve changelog from GitHub"); } - WriteVerbose("Successfully retrieved changelog from GitHub"); + LogDebug("Successfully retrieved changelog from GitHub"); var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); @@ -67,8 +68,8 @@ private string RetrieveLatestStableRelease(HttpClient httpClient) throw new PSInvalidOperationException("Failed to identify versions in changelog on GitHub"); } - WriteVerbose($"Found {releasedVersions.Count} released versions in changelog"); - WriteVerbose($"Looking for release information on previous stable version {releasedVersions[0].Groups["version"].Value}"); + LogDebug($"Found {releasedVersions.Count} released versions in changelog"); + LogDebug($"Looking for release information on previous stable version {releasedVersions[0].Groups["version"].Value}"); var match = Regex.Match(content, @$"(?## \[{releasedVersions[0].Groups["version"].Value.Replace(".", @"\.")}]\n.*?)\n## \[\d+?\.\d+?\.\d+?\]", RegexOptions.Singleline); @@ -90,7 +91,7 @@ private string RetrieveSpecificRelease(HttpClient httpClient, string version) { var url = "https://raw.githubusercontent.com/pnp/powershell/dev/CHANGELOG.md"; - WriteVerbose($"Retrieving changelog from {url}"); + LogDebug($"Retrieving changelog from {url}"); var response = httpClient.GetAsync(url).GetAwaiter().GetResult(); if (!response.IsSuccessStatusCode) @@ -98,11 +99,11 @@ private string RetrieveSpecificRelease(HttpClient httpClient, string version) throw new PSInvalidOperationException("Failed to retrieve changelog from GitHub"); } - WriteVerbose("Successfully retrieved changelog from GitHub"); + LogDebug("Successfully retrieved changelog from GitHub"); var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); - WriteVerbose($"Looking for release information on the {version} release"); + LogDebug($"Looking for release information on the {version} release"); var match = Regex.Match(content, @$"(?## \[{version}]\n.*?)\n## \[\d+?\.\d+?\.\d+?\]", RegexOptions.Singleline); diff --git a/src/Commands/Base/GetException.cs b/src/Commands/Base/GetException.cs index fe3cf7fc8..7c2c19eae 100644 --- a/src/Commands/Base/GetException.cs +++ b/src/Commands/Base/GetException.cs @@ -10,7 +10,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Get, "PnPException")] [OutputType(typeof(PnPException))] - public class GetException : PSCmdlet + public class GetException : BasePSCmdlet { [Parameter(Mandatory = false)] public SwitchParameter All; diff --git a/src/Commands/Base/GetManagedAppId.cs b/src/Commands/Base/GetManagedAppId.cs index 1e29bf453..368537dc4 100644 --- a/src/Commands/Base/GetManagedAppId.cs +++ b/src/Commands/Base/GetManagedAppId.cs @@ -5,7 +5,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Get, "PnPManagedAppId")] [OutputType(typeof(PSCredential))] - public class GetManagedAppId : PSCmdlet + public class GetManagedAppId : BasePSCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Url; @@ -20,7 +20,7 @@ protected override void ProcessRecord() } else { - WriteError(new ErrorRecord(new Exception("AppId not found"), "APPIDNOTFOUND", ErrorCategory.AuthenticationError, this)); + LogError("AppId not found"); } } } diff --git a/src/Commands/Base/GetStoredCredential.cs b/src/Commands/Base/GetStoredCredential.cs index ecd91068e..b5fcf03fb 100644 --- a/src/Commands/Base/GetStoredCredential.cs +++ b/src/Commands/Base/GetStoredCredential.cs @@ -4,7 +4,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Get, "PnPStoredCredential")] [OutputType(typeof(PSCredential))] - public class GetStoredCredential : PSCmdlet + public class GetStoredCredential : BasePSCmdlet { [Parameter(Mandatory = true)] public string Name; @@ -18,7 +18,7 @@ protected override void ProcessRecord() } else { - WriteError(new ErrorRecord(new System.Exception("Credentials not found"), "CREDSNOTFOUND", ErrorCategory.AuthenticationError, this)); + LogError(new System.Exception("Credentials not found")); } } } diff --git a/src/Commands/Base/GetTraceLog.cs b/src/Commands/Base/GetTraceLog.cs index dfe36dd05..6ce1e9128 100644 --- a/src/Commands/Base/GetTraceLog.cs +++ b/src/Commands/Base/GetTraceLog.cs @@ -1,16 +1,46 @@ +using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Management.Automation; -using PnP.PowerShell.Model; +using PnP.PowerShell.Commands.Utilities.Logging; namespace PnP.PowerShell.Commands.Base { - [Cmdlet(VerbsCommon.Get, "PnPTraceLog")] - public class GetTraceLog : PSCmdlet + [Cmdlet(VerbsCommon.Get, "PnPTraceLog", DefaultParameterSetName = ParameterSet_LOGFROMLOGSTREAM)] + [OutputType(typeof(IEnumerable))] + public class GetTraceLog : BasePSCmdlet { - [Parameter(Mandatory = false, Position = 0, ValueFromPipeline = true, ParameterSetName = "On")] + private const string ParameterSet_LOGFROMFILE = "Log from file"; + private const string ParameterSet_LOGFROMLOGSTREAM = "Log from log stream"; + + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = ParameterSet_LOGFROMFILE)] public string Path; protected override void ProcessRecord() + { + switch (ParameterSetName) + { + case ParameterSet_LOGFROMLOGSTREAM: + ProcessLogFromLogStream(); + break; + case ParameterSet_LOGFROMFILE: + ProcessLogFromFile(); + break; + } + } + + private void ProcessLogFromLogStream() + { + LogDebug("Retrieving log entries from log stream"); + var logStreamListener = Trace.Listeners[LogStreamListener.DefaultListenerName] as LogStreamListener ?? throw new PSArgumentException($"Log stream listener {LogStreamListener.DefaultListenerName} not found"); + + foreach (var entry in logStreamListener.Entries) + { + WriteObject(entry, true); + } + } + + private void ProcessLogFromFile() { if (!System.IO.Path.IsPathRooted(Path)) { @@ -18,17 +48,18 @@ protected override void ProcessRecord() } if (File.Exists(Path)) { - var lines = System.IO.File.ReadAllLines(Path); + LogDebug($"Retrieving log entries from file {Path}"); + var lines = File.ReadAllLines(Path); foreach (var line in lines) { - var items = line.Split('\t'); + var items = line.Split(" : ")[1].Split('\t'); WriteObject(new TraceLogEntry(items), true); } - } else { + } + else + { throw new PSArgumentException($"File {Path} does not exist"); } } - - } } \ No newline at end of file diff --git a/src/Commands/Base/NewAzureCertificate.cs b/src/Commands/Base/NewAzureCertificate.cs index d647e38b7..eb2c5224c 100644 --- a/src/Commands/Base/NewAzureCertificate.cs +++ b/src/Commands/Base/NewAzureCertificate.cs @@ -9,7 +9,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.New, "PnPAzureCertificate")] [OutputType(typeof(Model.AzureCertificate))] - public class NewPnPAdalCertificate : PSCmdlet + public class NewPnPAdalCertificate : BasePSCmdlet { [Parameter(Mandatory = false, Position = 0)] public string CommonName = "pnp.contoso.com"; @@ -104,7 +104,7 @@ protected override void ProcessRecord() Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, "Certificate added to store"); } - GetPnPAdalCertificate.WriteAzureCertificateOutput(this, certificate, CertificatePassword); + GetPnPAzureCertificate.WriteAzureCertificateOutput(this, certificate, CertificatePassword); } } } diff --git a/src/Commands/Base/PipeBinds/ContentTypePipeBind.cs b/src/Commands/Base/PipeBinds/ContentTypePipeBind.cs index eca2abe32..70a6407d3 100644 --- a/src/Commands/Base/PipeBinds/ContentTypePipeBind.cs +++ b/src/Commands/Base/PipeBinds/ContentTypePipeBind.cs @@ -84,30 +84,30 @@ internal string GetIdOrThrow(string paramName, PnPCore.IList list) => GetId(list) ?? throw new PSArgumentException(NotFoundMessage(list), paramName); - public string GetIdOrWarn(Cmdlet cmdlet, Web web, bool searchInSiteHierarchy = true) + public string GetIdOrWarn(BasePSCmdlet cmdlet, Web web, bool searchInSiteHierarchy = true) { var id = GetId(web, searchInSiteHierarchy); if (id is null) - cmdlet.WriteWarning(NotFoundMessage(searchInSiteHierarchy)); + cmdlet.LogWarning(NotFoundMessage(searchInSiteHierarchy)); return id; } - public string GetIdOrWarn(Cmdlet cmdlet, PnP.Core.Services.PnPContext context, bool searchInSiteHierarchy = true) + public string GetIdOrWarn(BasePSCmdlet cmdlet, Core.Services.PnPContext context, bool searchInSiteHierarchy = true) { var id = GetId(context, searchInSiteHierarchy); if (id is null) - cmdlet.WriteWarning(NotFoundMessage(searchInSiteHierarchy)); + cmdlet.LogWarning(NotFoundMessage(searchInSiteHierarchy)); return id; } - public string GetIdOrWarn(Cmdlet cmdlet, List list) + public string GetIdOrWarn(BasePSCmdlet cmdlet, List list) { var id = GetId(list); if (id is null) { - cmdlet.WriteWarning(NotFoundMessage(list)); + cmdlet.LogWarning(NotFoundMessage(list)); } return id; @@ -129,7 +129,7 @@ internal ContentType GetContentType(Web web, bool searchInSiteHierarchy = true) return web.GetContentTypeByName(_idOrName, searchInSiteHierarchy); } - internal PnPCore.IContentType GetContentType(PnP.Core.Services.PnPContext context, bool searchInSiteHierarchy = true) + internal PnPCore.IContentType GetContentType(Core.Services.PnPContext context, bool searchInSiteHierarchy = true) { if (_coreContentType is object) { @@ -240,20 +240,20 @@ internal PnPCore.IContentType GetContentTypeOrThrow(string paramName, PnP.Core.S => GetContentType(context, searchInSiteHierarchy) ?? throw new PSArgumentException(NotFoundMessage(searchInSiteHierarchy), paramName); - internal ContentType GetContentTypeOrError(Cmdlet cmdlet, string paramName, Web web, bool searchInSiteHierarchy = true) + internal ContentType GetContentTypeOrError(BasePSCmdlet cmdlet, string paramName, Web web, bool searchInSiteHierarchy = true) { var ct = GetContentType(web, searchInSiteHierarchy); if (ct is null) - cmdlet.WriteError(new ErrorRecord(new PSArgumentException(NotFoundMessage(searchInSiteHierarchy), paramName), "CONTENTTYPEDOESNOTEXIST", ErrorCategory.InvalidArgument, this)); + cmdlet.LogError(new PSArgumentException(NotFoundMessage(searchInSiteHierarchy), paramName)); return ct; } - internal PnPCore.IContentType GetContentTypeOrError(Cmdlet cmdlet, string paramName, PnP.Core.Services.PnPContext context, bool searchInSiteHierarchy = true) + internal PnPCore.IContentType GetContentTypeOrError(BasePSCmdlet cmdlet, string paramName, PnP.Core.Services.PnPContext context, bool searchInSiteHierarchy = true) { var ct = GetContentType(context, searchInSiteHierarchy); if (ct is null) { - cmdlet.WriteError(new ErrorRecord(new PSArgumentException(NotFoundMessage(searchInSiteHierarchy), paramName), "CONTENTTYPEDOESNOTEXIST", ErrorCategory.InvalidArgument, this)); + cmdlet.LogError(new PSArgumentException(NotFoundMessage(searchInSiteHierarchy), paramName)); } return ct; } @@ -262,63 +262,63 @@ internal ContentType GetContentTypeOrThrow(string paramName, List list) => GetContentType(list) ?? throw new PSArgumentException(NotFoundMessage(list), paramName); - internal ContentType GetContentTypeOrError(Cmdlet cmdlet, string paramName, List list) + internal ContentType GetContentTypeOrError(BasePSCmdlet cmdlet, string paramName, List list) { var ct = GetContentType(list); if (ct is null) - cmdlet.WriteError(new ErrorRecord(new PSArgumentException(NotFoundMessage(list), paramName), "CONTENTTYPEDOESNOTEXIST", ErrorCategory.InvalidArgument, this)); + cmdlet.LogError(new PSArgumentException(NotFoundMessage(list), paramName)); return ct; } - internal PnPCore.IContentType GetContentTypeOrError(Cmdlet cmdlet, string paramName, PnPCore.IList list) + internal PnPCore.IContentType GetContentTypeOrError(BasePSCmdlet cmdlet, string paramName, PnPCore.IList list) { var ct = GetContentType(list); if (ct is null) - cmdlet.WriteError(new ErrorRecord(new PSArgumentException(NotFoundMessage(list), paramName), "CONTENTTYPEDOESNOTEXIST", ErrorCategory.InvalidArgument, this)); + cmdlet.LogError(new PSArgumentException(NotFoundMessage(list), paramName)); return ct; } - internal ContentType GetContentTypeOrWarn(Cmdlet cmdlet, Web web, bool searchInSiteHierarchy = true) + internal ContentType GetContentTypeOrWarn(BasePSCmdlet cmdlet, Web web, bool searchInSiteHierarchy = true) { var ct = GetContentType(web, searchInSiteHierarchy); if (ct is null) - cmdlet.WriteWarning(NotFoundMessage(searchInSiteHierarchy)); + cmdlet.LogWarning(NotFoundMessage(searchInSiteHierarchy)); return ct; } - internal PnPCore.IContentType GetContentTypeOrWarn(Cmdlet cmdlet, PnP.Core.Services.PnPContext context, bool searchInSiteHierarchy = true) + internal PnPCore.IContentType GetContentTypeOrWarn(BasePSCmdlet cmdlet, Core.Services.PnPContext context, bool searchInSiteHierarchy = true) { var ct = GetContentType(context, searchInSiteHierarchy); if (ct is null) - cmdlet.WriteWarning(NotFoundMessage(searchInSiteHierarchy)); + cmdlet.LogWarning(NotFoundMessage(searchInSiteHierarchy)); return ct; } - internal ContentType GetContentTypeOrWarn(Cmdlet cmdlet, List list) + internal ContentType GetContentTypeOrWarn(BasePSCmdlet cmdlet, List list) { var ct = GetContentType(list); if (ct is null) - cmdlet.WriteWarning(NotFoundMessage(list)); + cmdlet.LogWarning(NotFoundMessage(list)); return ct; } - internal PnPCore.IContentType GetContentTypeOrWarn(Cmdlet cmdlet, PnPCore.IList list) + internal PnPCore.IContentType GetContentTypeOrWarn(BasePSCmdlet cmdlet, PnPCore.IList list) { var ct = GetContentType(list); if (ct is null) - cmdlet.WriteWarning(NotFoundMessage(list)); + cmdlet.LogWarning(NotFoundMessage(list)); return ct; } - internal PnP.Core.Model.SharePoint.IContentType GetContentTypeOrWarn(Cmdlet cmdlet, PnPBatch batch, PnP.Core.Model.SharePoint.IList list) + internal PnP.Core.Model.SharePoint.IContentType GetContentTypeOrWarn(BasePSCmdlet cmdlet, PnPBatch batch, PnP.Core.Model.SharePoint.IList list) { var ct = GetContentType(batch, list); if (ct is null) - cmdlet.WriteWarning(NotFoundMessage(list)); + cmdlet.LogWarning(NotFoundMessage(list)); return ct; } diff --git a/src/Commands/Base/PipeBinds/ListPipeBind.cs b/src/Commands/Base/PipeBinds/ListPipeBind.cs index 3caab34a8..62608aa39 100644 --- a/src/Commands/Base/PipeBinds/ListPipeBind.cs +++ b/src/Commands/Base/PipeBinds/ListPipeBind.cs @@ -194,17 +194,17 @@ internal List GetListOrThrow(string paramName, Web selectedWeb, params System.Li return GetList(selectedWeb, retrievals) ?? throw new PSArgumentException(NoListMessage, paramName); } - internal PnPCore.IList GetListOrThrow(string paramName, PnP.Core.Services.PnPContext context, params System.Linq.Expressions.Expression>[] retrievals) + internal PnPCore.IList GetListOrThrow(string paramName, Core.Services.PnPContext context, params System.Linq.Expressions.Expression>[] retrievals) { return GetList(context, retrievals) ?? throw new PSArgumentException(NoListMessage, paramName); } - internal List GetListOrWarn(Cmdlet cmdlet, Web web, params System.Linq.Expressions.Expression>[] retrievals) + internal List GetListOrWarn(BasePSCmdlet cmdlet, Web web, params System.Linq.Expressions.Expression>[] retrievals) { var list = GetList(web, retrievals); if (list is null) { - cmdlet.WriteWarning(NoListMessage); + cmdlet.LogWarning(NoListMessage); } return list; diff --git a/src/Commands/Base/PipeBinds/VivaACEPipeBind.cs b/src/Commands/Base/PipeBinds/VivaACEPipeBind.cs index b9afc2192..273051998 100644 --- a/src/Commands/Base/PipeBinds/VivaACEPipeBind.cs +++ b/src/Commands/Base/PipeBinds/VivaACEPipeBind.cs @@ -47,7 +47,7 @@ public AdaptiveCardExtension GetACE(IVivaDashboard dashboard, PnPWebCmdlet cmdle } else { - cmdlet.WriteWarning("Multiple ACEs found with the same title, please use instance id"); + cmdlet.LogWarning("Multiple ACEs found with the same title, please use instance id"); } } if (_id != Guid.Empty) @@ -63,7 +63,7 @@ public AdaptiveCardExtension GetACE(IVivaDashboard dashboard, PnPWebCmdlet cmdle } else { - cmdlet.WriteWarning("Multiple ACEs found of the same type, please use instance id"); + cmdlet.LogWarning("Multiple ACEs found of the same type, please use instance id"); } } } diff --git a/src/Commands/Base/PnPConnectedCmdlet.cs b/src/Commands/Base/PnPConnectedCmdlet.cs index 09c56bda7..6e32f1b53 100644 --- a/src/Commands/Base/PnPConnectedCmdlet.cs +++ b/src/Commands/Base/PnPConnectedCmdlet.cs @@ -113,13 +113,8 @@ protected override void ProcessRecord() { ex.Data["CorrelationId"] = Connection.Context.TraceCorrelationId; ex.Data["TimeStampUtc"] = DateTime.UtcNow; - var errorDetails = new ErrorDetails(errorMessage); - errorDetails.RecommendedAction = "Use Get-PnPException for more details."; - var errorRecord = new ErrorRecord(ex, "EXCEPTION", ErrorCategory.WriteError, null); - errorRecord.ErrorDetails = errorDetails; - - WriteError(errorRecord); + LogError(errorMessage); } } diff --git a/src/Commands/Base/PnPConnection.cs b/src/Commands/Base/PnPConnection.cs index 0e4883a8b..f5c82e379 100644 --- a/src/Commands/Base/PnPConnection.cs +++ b/src/Commands/Base/PnPConnection.cs @@ -281,7 +281,7 @@ internal static PnPConnection CreateWithDeviceLogin(string clientId, string url, authManager = Framework.AuthenticationManager.CreateWithDeviceLogin(clientId, tenantId, (deviceCodeResult) => { ClipboardService.SetText(deviceCodeResult.UserCode); - messageWriter.WriteWarning($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard and a new tab in the browser has been opened. Please paste this code in there and proceed.\n\n"); + messageWriter.LogWarning($"\n\nCode {deviceCodeResult.UserCode} has been copied to your clipboard and a new tab in the browser has been opened. Please paste this code in there and proceed.\n\n"); BrowserHelper.OpenBrowserForInteractiveLogin(deviceCodeResult.VerificationUrl, BrowserHelper.FindFreeLocalhostRedirectUri(), cancellationTokenSource); return Task.FromResult(0); @@ -380,11 +380,11 @@ internal static PnPConnection CreateWithManagedIdentity(string url, string tenan { var endPoint = Environment.GetEnvironmentVariable("IDENTITY_ENDPOINT"); PnP.Framework.Diagnostics.Log.Debug("PnPConnection", $"Using identity endpoint: {endPoint}"); - //cmdlet.WriteVerbose($"Using identity endpoint: {endPoint}"); + //cmdlet.LogDebug($"Using identity endpoint: {endPoint}"); var identityHeader = Environment.GetEnvironmentVariable("IDENTITY_HEADER"); PnP.Framework.Diagnostics.Log.Debug("PnPConnection", $"Using identity header: {identityHeader}"); - //cmdlet.WriteVerbose($"Using identity header: {identityHeader}"); + //cmdlet.LogDebug($"Using identity header: {identityHeader}"); if (string.IsNullOrEmpty(endPoint)) { diff --git a/src/Commands/Base/PnPSharePointCmdlet.cs b/src/Commands/Base/PnPSharePointCmdlet.cs index 115dce7cc..60b4e3e48 100644 --- a/src/Commands/Base/PnPSharePointCmdlet.cs +++ b/src/Commands/Base/PnPSharePointCmdlet.cs @@ -65,7 +65,7 @@ protected string AccessToken } } } - WriteVerbose("Unable to acquire token for resource " + Connection.Url); + LogDebug("Unable to acquire token for resource " + Connection.Url); return null; } } @@ -88,7 +88,7 @@ public string GraphAccessToken return TokenHandler.GetAccessToken($"https://{Connection.GraphEndPoint}/.default", Connection); } } - WriteVerbose("Unable to acquire token for resource " + Connection.GraphEndPoint); + LogDebug("Unable to acquire token for resource " + Connection.GraphEndPoint); return null; } } @@ -148,12 +148,12 @@ protected void PollOperation(SpoOperation spoOperation) { if (spoOperation.IsComplete) { - WriteVerbose("Operation completed"); + LogDebug("Operation completed"); return; } if (spoOperation.HasTimedout) { - WriteVerbose("Operation timed out"); + LogDebug("Operation timed out"); throw new TimeoutException("SharePoint Operation Timeout"); } @@ -164,11 +164,11 @@ protected void PollOperation(SpoOperation spoOperation) break; } - WriteVerbose("Checking for operation status"); + LogDebug("Checking for operation status"); ClientContext.Load(spoOperation); ClientContext.ExecuteQueryRetry(); } - WriteWarning("SharePoint Operation Wait Interrupted"); + LogWarning("SharePoint Operation Wait Interrupted"); } } } diff --git a/src/Commands/Base/PnPSharePointOnlineAdminCmdlet.cs b/src/Commands/Base/PnPSharePointOnlineAdminCmdlet.cs index c40787d0c..7693a7735 100644 --- a/src/Commands/Base/PnPSharePointOnlineAdminCmdlet.cs +++ b/src/Commands/Base/PnPSharePointOnlineAdminCmdlet.cs @@ -106,7 +106,7 @@ protected override void BeginProcessing() else { // The current connection has been made to the SharePoint Online Admin Center URL already, we can use it as is - WriteVerbose($"Already connect to the SharePoint Online Admin Center at '{ClientContext.Url}'"); + LogDebug($"Already connect to the SharePoint Online Admin Center at '{ClientContext.Url}'"); BaseUri = new Uri($"{uri.Scheme}://{uriParts[0].ToLower().Replace("-admin", "")}{(uriParts.Length > 1 ? $".{string.Join(".", uriParts.Skip(1))}" : string.Empty)}{(!uri.IsDefaultPort ? ":" + uri.Port : "")}"); AdminContext = ClientContext; return; @@ -117,7 +117,7 @@ protected override void BeginProcessing() IsDeviceLogin(tenantAdminUrl); // Set up a temporary context to the SharePoint Online Admin Center URL to allow this cmdlet to execute - WriteVerbose($"Connecting to the SharePoint Online Admin Center at '{tenantAdminUrl}' to run this cmdlet"); + LogDebug($"Connecting to the SharePoint Online Admin Center at '{tenantAdminUrl}' to run this cmdlet"); try { AdminContext = Connection.CloneContext(tenantAdminUrl); @@ -130,7 +130,7 @@ protected override void BeginProcessing() { throw new PSInvalidOperationException($"Unable to connect to the SharePoint Online Admin Center at '{tenantAdminUrl}' to run this cmdlet. If this URL is incorrect for your tenant, you can pass in the correct Admin Center URL using Connect-PnPOnline -TenantAdminUrl. If you are using Privileged Identity Management (PIM) on your tenant, please ensure you have activated at least the SharePoint Administrator role and allowed some time for it to activate. Error message: {e.Message}", e); } - WriteVerbose($"Connected to the SharePoint Online Admin Center at '{tenantAdminUrl}' to run this cmdlet"); + LogDebug($"Connected to the SharePoint Online Admin Center at '{tenantAdminUrl}' to run this cmdlet"); SharePointOnlineAdminRequestHelper = new ApiRequestHelper(GetType(), Connection, MicrosoftSharePointOnlineAdminDefaultAudience); } diff --git a/src/Commands/Base/RemoveManagedAppId.cs b/src/Commands/Base/RemoveManagedAppId.cs index 3b67a8048..7deb7c2a1 100644 --- a/src/Commands/Base/RemoveManagedAppId.cs +++ b/src/Commands/Base/RemoveManagedAppId.cs @@ -5,7 +5,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Remove, "PnPManagedAppId")] [OutputType(typeof(void))] - public class RemoveManagedAppId : PSCmdlet + public class RemoveManagedAppId : BasePSCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Url; @@ -23,13 +23,13 @@ protected override void ProcessRecord() { if (!Utilities.CredentialManager.RemoveAppid(uri.ToString())) { - WriteError(new ErrorRecord(new Exception($"AppId for {Url} not removed"), "APPIDNOTREMOVED", ErrorCategory.WriteError, Url)); + LogError($"AppId for {Url} not removed"); } } } else { - WriteError(new ErrorRecord(new Exception($"AppId not found for {Url}"), "APPIDNOTFOUND", ErrorCategory.ObjectNotFound, Url)); + LogError($"AppId not found for {Url}"); } } } diff --git a/src/Commands/Base/RemoveStoredCredential.cs b/src/Commands/Base/RemoveStoredCredential.cs index 95c74b787..48fb55905 100644 --- a/src/Commands/Base/RemoveStoredCredential.cs +++ b/src/Commands/Base/RemoveStoredCredential.cs @@ -4,7 +4,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Remove, "PnPStoredCredential")] [OutputType(typeof(void))] - public class RemoveStoredCredential : PSCmdlet + public class RemoveStoredCredential : BasePSCmdlet { [Parameter(Mandatory = true)] public string Name; @@ -21,13 +21,13 @@ protected override void ProcessRecord() { if (!Utilities.CredentialManager.RemoveCredential(Name)) { - WriteError(new ErrorRecord(new System.Exception($"Credential {Name} not removed"), "CREDENTIALNOTREMOVED", ErrorCategory.WriteError, Name)); + LogError($"Credential {Name} not removed"); } } } else { - WriteError(new ErrorRecord(new System.Exception($"Credential {Name} not found"), "CREDENTIALNOTFOUND", ErrorCategory.ObjectNotFound, Name)); + LogError($"Credential {Name} not found"); } } } diff --git a/src/Commands/Base/SetManagedAppId.cs b/src/Commands/Base/SetManagedAppId.cs index 9cfde567a..87f652dea 100644 --- a/src/Commands/Base/SetManagedAppId.cs +++ b/src/Commands/Base/SetManagedAppId.cs @@ -5,7 +5,7 @@ namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Set, "PnPManagedAppId")] [OutputType(typeof(void))] - public class SetManagedAppId : PSCmdlet + public class SetManagedAppId : BasePSCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Url; @@ -15,6 +15,11 @@ public class SetManagedAppId : PSCmdlet [Parameter(Mandatory = false)] public SwitchParameter Overwrite; + + public SetManagedAppId() + { + } + protected override void ProcessRecord() { Uri uri = new Uri(Url); diff --git a/src/Commands/Base/StartTraceLog.cs b/src/Commands/Base/StartTraceLog.cs index 605e408e9..75a885bff 100644 --- a/src/Commands/Base/StartTraceLog.cs +++ b/src/Commands/Base/StartTraceLog.cs @@ -1,12 +1,11 @@ - -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Management.Automation; +using PnP.PowerShell.Commands.Utilities.Logging; namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsLifecycle.Start, "PnPTraceLog")] - public class StartTraceLog : PSCmdlet + public class StartTraceLog : BasePSCmdlet { [Parameter(Mandatory = false)] public string Path; @@ -14,6 +13,9 @@ public class StartTraceLog : PSCmdlet [Parameter(Mandatory = false)] public SwitchParameter WriteToConsole; + [Parameter(Mandatory = false)] + public SwitchParameter WriteToLogStream; + [Parameter(Mandatory = false)] public Framework.Diagnostics.LogLevel Level = Framework.Diagnostics.LogLevel.Information; @@ -25,59 +27,52 @@ public class StartTraceLog : PSCmdlet protected override void ProcessRecord() { + Framework.Diagnostics.Log.LogLevel = Level; + if (WriteToConsole.ToBool()) { - RemoveListener(ConsoleListenername); + LogDebug($"Adding console listener named {ConsoleListenername}"); + + LoggingUtility.RemoveListener(ConsoleListenername); ConsoleTraceListener consoleListener = new(false) { Name = ConsoleListenername }; Trace.Listeners.Add(consoleListener); - Framework.Diagnostics.Log.LogLevel = Level; + } + + if (WriteToLogStream.ToBool()) + { + LogDebug($"Adding log stream listener named {LogStreamListener.DefaultListenerName}"); + + LoggingUtility.RemoveListener(LogStreamListener.DefaultListenerName); + LogStreamListener logStreamListener = new() + { + Name = LogStreamListener.DefaultListenerName + }; + Trace.Listeners.Add(logStreamListener); } if (!string.IsNullOrEmpty(Path)) { - RemoveListener(FileListenername); + LoggingUtility.RemoveListener(FileListenername); if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } - // Create DelimitedListTraceListener in case Delimiter parameter has been specified, if not create TextWritterTraceListener + + LogDebug($"Adding file listener named {FileListenername} to {Path}"); + TraceListener listener = new TextWriterTraceListener(Path) { Name = FileListenername }; Trace.Listeners.Add(listener); - Framework.Diagnostics.Log.LogLevel = Level; } Trace.AutoFlush = AutoFlush; Trace.IndentSize = 4; } - - /// - /// Tries to remove the listener with the given name from the Trace.Listeners collection. - /// If the listener is not found, it will be ignored. - /// - /// Name of the trace listener - private static void RemoveListener(string listenerName) - { - try - { - var existingListener = Trace.Listeners[listenerName]; - if (existingListener != null) - { - existingListener.Flush(); - existingListener.Close(); - Trace.Listeners.Remove(existingListener); - } - } - catch (Exception) - { - // ignored - } - } } } \ No newline at end of file diff --git a/src/Commands/Base/StopTraceLog.cs b/src/Commands/Base/StopTraceLog.cs index edfbb6b07..b03cbd029 100644 --- a/src/Commands/Base/StopTraceLog.cs +++ b/src/Commands/Base/StopTraceLog.cs @@ -1,39 +1,45 @@  -using System; using System.Diagnostics; using System.Management.Automation; +using PnP.PowerShell.Commands.Utilities.Logging; namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsLifecycle.Stop, "PnPTraceLog")] - public class StopTraceLog : PSCmdlet + public class StopTraceLog : BasePSCmdlet { + [Parameter(Mandatory = false)] + public SwitchParameter StopFileLogging = true; + + [Parameter(Mandatory = false)] + public SwitchParameter StopConsoleLogging = true; + + [Parameter(Mandatory = false)] + public SwitchParameter StopLogStreamLogging = true; + private const string FileListenername = "PNPPOWERSHELLFILETRACELISTENER"; private const string ConsoleListenername = "PNPPOWERSHELLCONSOLETRACELISTENER"; + protected override void ProcessRecord() { + LogDebug("Flushing log entries"); Trace.Flush(); - RemoveListener(ConsoleListenername); - RemoveListener(FileListenername); - } - private void RemoveListener(string listenerName) - { - try + if (StopConsoleLogging.ToBool()) { - var existingListener = Trace.Listeners[listenerName]; - if (existingListener != null) - { - existingListener.Flush(); - existingListener.Close(); - Trace.Listeners.Remove(existingListener); - } + LogDebug("Stopping logging to console"); + LoggingUtility.RemoveListener(ConsoleListenername); } - catch (Exception) + if (StopFileLogging.ToBool()) { - // ignored + LogDebug("Stopping logging to file"); + LoggingUtility.RemoveListener(FileListenername); + } + if(StopLogStreamLogging.ToBool()) + { + LogDebug("Stopping logging to in memory log stream"); + LoggingUtility.RemoveListener(LogStreamListener.DefaultListenerName); } - } } } \ No newline at end of file diff --git a/src/Commands/Base/TokenHandler.cs b/src/Commands/Base/TokenHandler.cs index 4fca17769..ec4271147 100644 --- a/src/Commands/Base/TokenHandler.cs +++ b/src/Commands/Base/TokenHandler.cs @@ -147,7 +147,7 @@ internal static void EnsureRequiredPermissionsAvailableInAccessTokenAudience(Typ // Log a warning that the permission check failed. Deliberately not throwing an exception here, as the permission attributes might be wrong, thus will try to execute anyway. PnP.Framework.Diagnostics.Log.Error("TokenHandler",exceptionTextBuilder.ToString().Replace(Environment.NewLine," ")); - //cmdlet.WriteWarning(exceptionTextBuilder.ToString()); + //cmdlet.LogWarning(exceptionTextBuilder.ToString()); } /// @@ -166,7 +166,7 @@ internal static string GetAccessToken(string audience, PnPConnection connection) if (connection.ConnectionMethod == ConnectionMethod.AzureADWorkloadIdentity) { PnP.Framework.Diagnostics.Log.Debug("TokenHandler",$"Acquiring token for resource {connection.GraphEndPoint} using Azure AD Workload Identity"); - //cmdlet.WriteVerbose("Acquiring token for resource " + connection.GraphEndPoint + " using Azure AD Workload Identity"); + //cmdlet.LogDebug("Acquiring token for resource " + connection.GraphEndPoint + " using Azure AD Workload Identity"); accessToken = GetAzureADWorkloadIdentityTokenAsync($"{audience.TrimEnd('/')}/.default").GetAwaiter().GetResult(); } else @@ -190,7 +190,7 @@ internal static string GetAccessToken(string audience, PnPConnection connection) if (string.IsNullOrEmpty(accessToken)) { PnP.Framework.Diagnostics.Log.Debug("TokenHandler",$"Unable to acquire token for resource {connection.GraphEndPoint}"); - //cmdlet.WriteVerbose($"Unable to acquire token for resource {connection.GraphEndPoint}"); + //cmdlet.LogDebug($"Unable to acquire token for resource {connection.GraphEndPoint}"); return null; } diff --git a/src/Commands/Base/WriteTraceLog.cs b/src/Commands/Base/WriteTraceLog.cs new file mode 100644 index 000000000..ba108358f --- /dev/null +++ b/src/Commands/Base/WriteTraceLog.cs @@ -0,0 +1,44 @@ +using System; +using System.Management.Automation; + +namespace PnP.PowerShell.Commands.Base +{ + [Cmdlet(VerbsCommunications.Write, "PnPTraceLog")] + [OutputType(typeof(void))] + public class WriteTraceLog : BasePSCmdlet + { + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] + public string Message; + + [Parameter(Mandatory = false)] + public string Source; + + [Parameter(Mandatory = false)] + public long? EllapsedMilliseconds; + + [Parameter(Mandatory = false)] + public override Guid? CorrelationId { get; protected set; } = null; + + [Parameter(Mandatory = false)] + public Framework.Diagnostics.LogLevel Level = Framework.Diagnostics.LogLevel.Information; + + protected override void ProcessRecord() + { + switch (Level) + { + case Framework.Diagnostics.LogLevel.Debug: + Utilities.Logging.LoggingUtility.Debug(this, Message, Source, CorrelationId, EllapsedMilliseconds); + break; + case Framework.Diagnostics.LogLevel.Warning: + Utilities.Logging.LoggingUtility.Warning(this, Message, Source, CorrelationId, EllapsedMilliseconds); + break; + case Framework.Diagnostics.LogLevel.Information: + Utilities.Logging.LoggingUtility.Info(this, Message, Source, CorrelationId, EllapsedMilliseconds); + break; + case Framework.Diagnostics.LogLevel.Error: + Utilities.Logging.LoggingUtility.Error(this, Message, Source, CorrelationId, EllapsedMilliseconds); + break; + } + } + } +} \ No newline at end of file diff --git a/src/Commands/Branding/AddCustomAction.cs b/src/Commands/Branding/AddCustomAction.cs index baf5997b4..b0d2b3de2 100644 --- a/src/Commands/Branding/AddCustomAction.cs +++ b/src/Commands/Branding/AddCustomAction.cs @@ -128,7 +128,7 @@ protected override void ExecuteCmdlet() break; } case CustomActionScope.All: - WriteWarning("CustomActionScope 'All' is not supported for adding CustomActions"); + LogWarning("CustomActionScope 'All' is not supported for adding CustomActions"); break; } } diff --git a/src/Commands/Branding/GetTheme.cs b/src/Commands/Branding/GetTheme.cs index 4bd5ec995..c9ea76888 100644 --- a/src/Commands/Branding/GetTheme.cs +++ b/src/Commands/Branding/GetTheme.cs @@ -17,7 +17,7 @@ protected override void ExecuteCmdlet() { try { - WriteWarning("The information presented here is based upon the fact that the theme has been set using either the PnP Provisioning Engine or using the Set-PnPTheme cmdlet. This information is retrieved from a propertybag value and may differ from the actual site."); + LogWarning("The information presented here is based upon the fact that the theme has been set using either the PnP Provisioning Engine or using the Set-PnPTheme cmdlet. This information is retrieved from a propertybag value and may differ from the actual site."); var composedLook = JsonSerializer.Deserialize(CurrentWeb.GetPropertyBagValueString("_PnP_ProvisioningTemplateComposedLookInfo", "")); WriteObject(composedLook); } diff --git a/src/Commands/Branding/SetHomepage.cs b/src/Commands/Branding/SetHomepage.cs index 8b4b44353..d31cd2900 100644 --- a/src/Commands/Branding/SetHomepage.cs +++ b/src/Commands/Branding/SetHomepage.cs @@ -13,11 +13,11 @@ protected override void ExecuteCmdlet() { if(RootFolderRelativeUrl.StartsWith("/")) { - WriteVerbose($"Removing leading / from {nameof(RootFolderRelativeUrl)}"); + LogDebug($"Removing leading / from {nameof(RootFolderRelativeUrl)}"); RootFolderRelativeUrl = RootFolderRelativeUrl.TrimStart('/'); } - WriteVerbose($"Setting homepage to {RootFolderRelativeUrl}"); + LogDebug($"Setting homepage to {RootFolderRelativeUrl}"); CurrentWeb.SetHomePage(RootFolderRelativeUrl); } } diff --git a/src/Commands/ContentTypes/GetContentTypePublishingStatus.cs b/src/Commands/ContentTypes/GetContentTypePublishingStatus.cs index b39738896..8f1cb54be 100644 --- a/src/Commands/ContentTypes/GetContentTypePublishingStatus.cs +++ b/src/Commands/ContentTypes/GetContentTypePublishingStatus.cs @@ -24,7 +24,7 @@ protected override void ExecuteCmdlet() if (ct == null) { - WriteError(new ErrorRecord(new Exception($"Invalid content type id."), "INVALIDCTID", ErrorCategory.InvalidArgument, ContentType)); + LogError("Invalid content type id."); return; } diff --git a/src/Commands/ContentTypes/PublishContentType.cs b/src/Commands/ContentTypes/PublishContentType.cs index d6f7ea958..28160ef0a 100644 --- a/src/Commands/ContentTypes/PublishContentType.cs +++ b/src/Commands/ContentTypes/PublishContentType.cs @@ -24,7 +24,7 @@ protected override void ExecuteCmdlet() if (ct == null) { - WriteError(new ErrorRecord(new Exception($"Invalid content type id."), "INVALIDCTID", ErrorCategory.InvalidArgument, ContentType)); + LogError("Invalid content type id."); return; } diff --git a/src/Commands/ContentTypes/SetContentType.cs b/src/Commands/ContentTypes/SetContentType.cs index 5a1afe3a2..dfd101d77 100644 --- a/src/Commands/ContentTypes/SetContentType.cs +++ b/src/Commands/ContentTypes/SetContentType.cs @@ -188,12 +188,12 @@ protected override void ExecuteCmdlet() { if (list != null) { - WriteVerbose("Updating content type on list"); + LogDebug("Updating content type on list"); ct.Update(false); } else { - WriteVerbose("Updating site content type"); + LogDebug("Updating site content type"); ct.Update(UpdateChildren); } ClientContext.ExecuteQueryRetry(); @@ -201,7 +201,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose("No changes to make"); + LogDebug("No changes to make"); } } } diff --git a/src/Commands/ContentTypes/UnpublishContentType.cs b/src/Commands/ContentTypes/UnpublishContentType.cs index 648df73f6..f4bcfa5bf 100644 --- a/src/Commands/ContentTypes/UnpublishContentType.cs +++ b/src/Commands/ContentTypes/UnpublishContentType.cs @@ -23,7 +23,7 @@ protected override void ExecuteCmdlet() if (ct == null) { - WriteError(new ErrorRecord(new Exception($"Invalid content type id."), "INVALIDCTID", ErrorCategory.InvalidArgument, ContentType)); + LogError("Invalid content type id."); return; } diff --git a/src/Commands/Copilot/SetCopilotAdminLimitedMode.cs b/src/Commands/Copilot/SetCopilotAdminLimitedMode.cs index 0ebaf7ad7..5a781a09e 100644 --- a/src/Commands/Copilot/SetCopilotAdminLimitedMode.cs +++ b/src/Commands/Copilot/SetCopilotAdminLimitedMode.cs @@ -29,7 +29,7 @@ protected override void ExecuteCmdlet() IsEnabledForGroup = IsEnabledForGroup }; var jsonContent = JsonContent.Create(bodyContent); - WriteVerbose($"Payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); + LogDebug($"Payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); var result = GraphRequestHelper.Patch("beta/copilot/admin/settings/limitedMode", jsonContent); WriteObject(result, false); diff --git a/src/Commands/Diagnostic/MeasurePnPList.cs b/src/Commands/Diagnostic/MeasurePnPList.cs index b8c381775..6c9101194 100644 --- a/src/Commands/Diagnostic/MeasurePnPList.cs +++ b/src/Commands/Diagnostic/MeasurePnPList.cs @@ -118,7 +118,7 @@ private FolderStatistics GetFolderStatistics(Folder folder, List list) if (folder.ListItemAllFields.HasUniqueRoleAssignments) { stat.BrokenPermissionCount++; - WriteVerbose($"Folder ${folder.ServerRelativeUrl} has unique permissions"); + LogDebug($"Folder ${folder.ServerRelativeUrl} has unique permissions"); } } diff --git a/src/Commands/Diagnostic/MeasurePnPWeb.cs b/src/Commands/Diagnostic/MeasurePnPWeb.cs index 86ee0150b..2cdf38fed 100644 --- a/src/Commands/Diagnostic/MeasurePnPWeb.cs +++ b/src/Commands/Diagnostic/MeasurePnPWeb.cs @@ -71,7 +71,7 @@ private FolderStatistics GetFolderStatistics(Folder folder) } catch (Exception e) { - WriteWarning($"Cannot inspect folder: {e.Message}"); + LogWarning($"Cannot inspect folder: {e.Message}"); } return stat; @@ -105,7 +105,7 @@ private WebStatistics GetStatistics(Web web) foreach (var list in uniqueLists) { - WriteVerbose($"List {list.Title} has unique permissions"); + LogDebug($"List {list.Title} has unique permissions"); } if (Recursive) diff --git a/src/Commands/DocumentSets/SetDocumentSetField.cs b/src/Commands/DocumentSets/SetDocumentSetField.cs index 3bc683c3c..359c6ed2e 100644 --- a/src/Commands/DocumentSets/SetDocumentSetField.cs +++ b/src/Commands/DocumentSets/SetDocumentSetField.cs @@ -34,12 +34,12 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(SetSharedField)) && ParameterSpecified(nameof(RemoveSharedField))) { - WriteWarning("Cannot set and remove a shared field at the same time"); + LogWarning("Cannot set and remove a shared field at the same time"); return; } if (ParameterSpecified(nameof(SetWelcomePageField)) && ParameterSpecified(nameof(RemoveWelcomePageField))) { - WriteWarning("Cannot set and remove a welcome page field at the same time"); + LogWarning("Cannot set and remove a welcome page field at the same time"); return; } @@ -111,7 +111,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Field not present in document set allowed content types"); + LogWarning("Field not present in document set allowed content types"); } } } diff --git a/src/Commands/Events/RemoveEventReceiver.cs b/src/Commands/Events/RemoveEventReceiver.cs index 03acd8eb2..1a7d5d005 100644 --- a/src/Commands/Events/RemoveEventReceiver.cs +++ b/src/Commands/Events/RemoveEventReceiver.cs @@ -117,7 +117,7 @@ protected override void ExecuteCmdlet() if (eventReceiversToDelete.Count == 0) { - WriteVerbose("No Event Receivers to remove"); + LogDebug("No Event Receivers to remove"); return; } @@ -127,7 +127,7 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue(string.Format(Properties.Resources.RemoveEventReceiver, eventReceiver.ReceiverName, eventReceiver.ReceiverId), Properties.Resources.Confirm)) { - WriteVerbose($"Removing Event Receiver with Id {eventReceiver.ReceiverId} named {eventReceiver.ReceiverName}"); + LogDebug($"Removing Event Receiver with Id {eventReceiver.ReceiverId} named {eventReceiver.ReceiverName}"); eventReceiver.DeleteObject(); } } diff --git a/src/Commands/Extensibility/NewExtensibilityHandlerObject.cs b/src/Commands/Extensibility/NewExtensibilityHandlerObject.cs index e34421cc3..9c702e78a 100644 --- a/src/Commands/Extensibility/NewExtensibilityHandlerObject.cs +++ b/src/Commands/Extensibility/NewExtensibilityHandlerObject.cs @@ -1,11 +1,12 @@ using System.Management.Automation; using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; namespace PnP.PowerShell.Commands.Extensibility { [Cmdlet(VerbsCommon.New, "PnPExtensibilityHandlerObject")] [OutputType(typeof(ExtensibilityHandler))] - public class NewExtensibilityHandlerObject : PSCmdlet + public class NewExtensibilityHandlerObject : BasePSCmdlet { [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] public string Assembly; diff --git a/src/Commands/Fields/SetField.cs b/src/Commands/Fields/SetField.cs index 45e9fcb06..d833c6207 100644 --- a/src/Commands/Fields/SetField.cs +++ b/src/Commands/Fields/SetField.cs @@ -34,7 +34,7 @@ protected override void ExecuteCmdlet() Field field = null; if (List != null) { - WriteVerbose("Retrieving provided list"); + LogDebug("Retrieving provided list"); var list = List.GetList(CurrentWeb); if (list == null) @@ -44,12 +44,12 @@ protected override void ExecuteCmdlet() if (Identity.Id != Guid.Empty) { - WriteVerbose($"Retrieving field by its ID {Identity.Id} from the list"); + LogDebug($"Retrieving field by its ID {Identity.Id} from the list"); field = list.Fields.GetById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Name)) { - WriteVerbose($"Retrieving field by its name {Identity.Name} from the list"); + LogDebug($"Retrieving field by its name {Identity.Name} from the list"); field = list.Fields.GetByInternalNameOrTitle(Identity.Name); } if (field == null) @@ -61,17 +61,17 @@ protected override void ExecuteCmdlet() { if (Identity.Id != Guid.Empty) { - WriteVerbose($"Retrieving field by its ID {Identity.Id} from the web"); + LogDebug($"Retrieving field by its ID {Identity.Id} from the web"); field = ClientContext.Web.Fields.GetById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Name)) { - WriteVerbose($"Retrieving field by its name {Identity.Name} from the web"); + LogDebug($"Retrieving field by its name {Identity.Name} from the web"); field = ClientContext.Web.Fields.GetByInternalNameOrTitle(Identity.Name); } else if (Identity.Field != null) { - WriteVerbose($"Using passed in field"); + LogDebug($"Using passed in field"); field = Identity.Field; } @@ -91,7 +91,7 @@ protected override void ExecuteCmdlet() } if(ShowInFiltersPane.HasValue) { - WriteVerbose($"Updating field to show in filters pane setting {ShowInFiltersPane.Value}"); + LogDebug($"Updating field to show in filters pane setting {ShowInFiltersPane.Value}"); field.ShowInFiltersPane = ShowInFiltersPane.Value; field.Update(); } @@ -99,7 +99,7 @@ protected override void ExecuteCmdlet() if (Values != null && Values.Count > 0) { - WriteVerbose($"Updating {Values.Count} field value{(Values.Count != 1 ? "s" : "")}"); + LogDebug($"Updating {Values.Count} field value{(Values.Count != 1 ? "s" : "")}"); // Get a reference to the type-specific object to allow setting type-specific properties, i.e. LookupList and LookupField for Microsoft.SharePoint.Client.FieldLookup var typeSpecificField = field.TypedObject; @@ -108,7 +108,7 @@ protected override void ExecuteCmdlet() { var value = Values[key]; - WriteVerbose($"Updating field {key} to {value}"); + LogDebug($"Updating field {key} to {value}"); var property = typeSpecificField.GetType().GetProperty(key); @@ -116,7 +116,7 @@ protected override void ExecuteCmdlet() if (property == null && !isAllowDeletionProperty) { - WriteWarning($"No property '{key}' found on this field. Value will be ignored."); + LogWarning($"No property '{key}' found on this field. Value will be ignored."); } else { @@ -133,7 +133,7 @@ protected override void ExecuteCmdlet() } catch (Exception e) { - WriteWarning($"Setting property '{key}' to '{value}' failed with exception '{e.Message}'. Value will be ignored."); + LogWarning($"Setting property '{key}' to '{value}' failed with exception '{e.Message}'. Value will be ignored."); } } } diff --git a/src/Commands/Files/AddFileSensitivityLabel.cs b/src/Commands/Files/AddFileSensitivityLabel.cs index 956daa723..10f1747b0 100644 --- a/src/Commands/Files/AddFileSensitivityLabel.cs +++ b/src/Commands/Files/AddFileSensitivityLabel.cs @@ -46,7 +46,7 @@ protected override void ExecuteCmdlet() HttpResponseHeaders responseHeader = RestHelper.PostGetResponseHeader(Connection.HttpClient, requestUrl, AccessToken, payload: payload); - WriteVerbose($"File sensitivity label assigned to {file.Name}"); + LogDebug($"File sensitivity label assigned to {file.Name}"); WriteObject(responseHeader.Location); } } diff --git a/src/Commands/Files/ConvertFile.cs b/src/Commands/Files/ConvertFile.cs index 4a7f3397c..5788caa0a 100644 --- a/src/Commands/Files/ConvertFile.cs +++ b/src/Commands/Files/ConvertFile.cs @@ -66,7 +66,7 @@ protected override void ExecuteCmdlet() IFile sourceFile = Connection.PnPContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl, p => p.VroomDriveID, p => p.VroomItemID); - WriteVerbose("Converting file to the specified format"); + LogDebug("Converting file to the specified format"); var convertedFile = sourceFile.ConvertTo(new ConvertToOptions { Format = ConvertToFormat }); var fileName = System.IO.Path.GetFileNameWithoutExtension(sourceFile.Name); @@ -79,11 +79,11 @@ protected override void ExecuteCmdlet() var fileOut = System.IO.Path.Combine(Path, newFileName); if (System.IO.File.Exists(fileOut) && !Force) { - WriteWarning($"File '{sourceFile.Name}' exists already. Use the -Force parameter to overwrite the file."); + LogWarning($"File '{sourceFile.Name}' exists already. Use the -Force parameter to overwrite the file."); } else { - WriteVerbose("Saving file to the disc."); + LogDebug("Saving file to the disc."); using FileStream fs = new(fileOut, FileMode.Create); convertedFile.CopyTo(fs); } @@ -99,7 +99,7 @@ protected override void ExecuteCmdlet() case UPLOADTOSHAREPOINT: - WriteVerbose("Uploading file to the specified folder"); + LogDebug("Uploading file to the specified folder"); var folder = EnsureFolder(); var uploadedFile = folder.UploadFile(newFileName, convertedFile, Force); @@ -117,7 +117,7 @@ protected override void ExecuteCmdlet() } WriteObject(uploadedFile); - WriteVerbose("File uploaded."); + LogDebug("File uploaded."); break; } diff --git a/src/Commands/Files/CopyFolder.cs b/src/Commands/Files/CopyFolder.cs index d94ffc3d5..b196fc0dc 100644 --- a/src/Commands/Files/CopyFolder.cs +++ b/src/Commands/Files/CopyFolder.cs @@ -99,12 +99,12 @@ private void CopyFromLocalToMicrosoft365() throw new PSArgumentException($"{nameof(LocalPath)} does not exist", nameof(LocalPath)); } - WriteVerbose($"Copying folder from local path {LocalPath} to Microsoft 365 location {UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, TargetUrl)}"); - WriteVerbose($"Retrieving local files {(Recurse.ToBool() ? "recursively " : "")}to upload from {LocalPath}"); + LogDebug($"Copying folder from local path {LocalPath} to Microsoft 365 location {UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, TargetUrl)}"); + LogDebug($"Retrieving local files {(Recurse.ToBool() ? "recursively " : "")}to upload from {LocalPath}"); var filesToCopy = System.IO.Directory.GetFiles(LocalPath, string.Empty, Recurse.ToBool() ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly); - WriteVerbose($"Uploading {filesToCopy.Length} file{(filesToCopy.Length != 1 ? "s" : "")}"); + LogDebug($"Uploading {filesToCopy.Length} file{(filesToCopy.Length != 1 ? "s" : "")}"); // Start with the root string currentRemotePath = null; @@ -133,33 +133,33 @@ private void CopyFromLocalToMicrosoft365() var newRemotePath = UrlUtility.Combine(TargetUrl, relativePath); - WriteVerbose($"* Ensuring remote folder {newRemotePath}"); + LogDebug($"* Ensuring remote folder {newRemotePath}"); folder = CurrentWeb.EnsureFolderPath(newRemotePath); } // Upload the file from local to remote - WriteVerbose($" * Uploading {fileToCopy} => {relativeLocalPathWithFileName}"); + LogDebug($" * Uploading {fileToCopy} => {relativeLocalPathWithFileName}"); try { folder.UploadFile(fileName, fileToCopy, Overwrite.ToBool()); if(RemoveAfterCopy.ToBool()) { - WriteVerbose($" * Removing {fileToCopy}"); + LogDebug($" * Removing {fileToCopy}"); System.IO.File.Delete(fileToCopy); } } catch(Exception ex) { - WriteWarning($"* Upload failed: {ex.Message}"); + LogWarning($"* Upload failed: {ex.Message}"); } } // Check if we should and can clean up folders no longer containing files if (RemoveAfterCopy.ToBool() && folderPathsToRemove.Count > 0) { - WriteVerbose($"Checking if {folderPathsToRemove.Count} folder{(folderPathsToRemove.Count != 1 ? "s" : "")} are empty and can be removed"); + LogDebug($"Checking if {folderPathsToRemove.Count} folder{(folderPathsToRemove.Count != 1 ? "s" : "")} are empty and can be removed"); // Reverse the list so we start with the deepest nested folder first folderPathsToRemove.Reverse(); @@ -168,19 +168,19 @@ private void CopyFromLocalToMicrosoft365() { if (System.IO.Directory.GetFiles(folderPathToRemove).Length == 0) { - WriteVerbose($"* Removing empty folder {folderPathToRemove}"); + LogDebug($"* Removing empty folder {folderPathToRemove}"); try { System.IO.Directory.Delete(folderPathToRemove); } catch(Exception ex) { - WriteWarning($"* Failed to remove empty folder {folderPathToRemove}: {ex.Message}"); + LogWarning($"* Failed to remove empty folder {folderPathToRemove}: {ex.Message}"); } } else { - WriteVerbose($"* Folder {folderPathToRemove} is not empty and thus will not be removed"); + LogDebug($"* Folder {folderPathToRemove} is not empty and thus will not be removed"); } } } @@ -202,7 +202,7 @@ private void CopyWithinMicrosoft365() SourceUrl = UrlUtility.Combine(CurrentWeb.ServerRelativeUrl, SourceUrl); } - WriteVerbose($"Copying folder within Microsoft 365 from {SourceUrl} to {TargetUrl}"); + LogDebug($"Copying folder within Microsoft 365 from {SourceUrl} to {TargetUrl}"); string sourceFolder = SourceUrl.Substring(0, SourceUrl.LastIndexOf('/')); string targetFolder = TargetUrl; diff --git a/src/Commands/Files/GetFile.cs b/src/Commands/Files/GetFile.cs index 116663b31..4a7495d03 100644 --- a/src/Commands/Files/GetFile.cs +++ b/src/Commands/Files/GetFile.cs @@ -98,7 +98,7 @@ protected override void ExecuteCmdlet() if (System.IO.File.Exists(fileOut) && !Force) { - WriteWarning($"File '{fileToDownloadName}' exists already. Use the -Force parameter to overwrite the file."); + LogWarning($"File '{fileToDownloadName}' exists already. Use the -Force parameter to overwrite the file."); } else { diff --git a/src/Commands/Files/GetFileInFolder.cs b/src/Commands/Files/GetFileInFolder.cs index f71b5f940..ac3ff51c7 100644 --- a/src/Commands/Files/GetFileInFolder.cs +++ b/src/Commands/Files/GetFileInFolder.cs @@ -125,7 +125,7 @@ private IEnumerable GetContentsByUrl(string FolderSiteRelativeUrl) { if(ParameterSpecified(nameof(ExcludeSystemFolders))) { - WriteWarning($"The {nameof(ExcludeSystemFolders)} parameter is only supported when retrieving a specific folder. It will be ignored."); + LogWarning($"The {nameof(ExcludeSystemFolders)} parameter is only supported when retrieving a specific folder. It will be ignored."); ExcludeSystemFolders = false; } targetFolder = CurrentWeb.EnsureProperty(w => w.RootFolder); @@ -162,7 +162,7 @@ private IEnumerable GetContentsByUrl(string FolderSiteRelativeUrl) { var relativeUrl = folder.ServerRelativeUrl.Remove(0, CurrentWeb.ServerRelativeUrl.Length); - WriteVerbose($"Processing folder {relativeUrl}"); + LogDebug($"Processing folder {relativeUrl}"); var subFolderContents = GetContentsByUrl(relativeUrl); folderContent = folderContent.Concat(subFolderContents); diff --git a/src/Commands/Files/GetFolder.cs b/src/Commands/Files/GetFolder.cs index 0c4cab3d5..af481a531 100644 --- a/src/Commands/Files/GetFolder.cs +++ b/src/Commands/Files/GetFolder.cs @@ -47,7 +47,7 @@ protected override void ExecuteCmdlet() { case ParameterSet_FOLDERSINCURRENTWEB: { - WriteVerbose("Getting all folders in the root of the current web"); + LogDebug("Getting all folders in the root of the current web"); ClientContext.Load(CurrentWeb, w => w.Folders.IncludeWithDefaultProperties(RetrievalExpressions)); ClientContext.ExecuteQueryRetry(); WriteObject(CurrentWeb.Folders, true); @@ -56,7 +56,7 @@ protected override void ExecuteCmdlet() case ParameterSet_CURRENTWEBROOTFOLDER: { - WriteVerbose("Getting root folder of the current web"); + LogDebug("Getting root folder of the current web"); folder = CurrentWeb.RootFolder; ReturnFolderProperties(folder); @@ -65,7 +65,7 @@ protected override void ExecuteCmdlet() case ParameterSet_LISTROOTFOLDER: { - WriteVerbose("Getting root folder of the provided list"); + LogDebug("Getting root folder of the provided list"); var list = ListRootFolder.GetList(CurrentWeb); folder = list.RootFolder; @@ -107,7 +107,7 @@ protected override void ExecuteCmdlet() case ParameterSet_FOLDERBYURL: { - WriteVerbose("Getting folder at the provided url"); + LogDebug("Getting folder at the provided url"); var webServerRelativeUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!Url.StartsWith(webServerRelativeUrl, StringComparison.OrdinalIgnoreCase)) { @@ -123,7 +123,7 @@ protected override void ExecuteCmdlet() private void ReturnFolderProperties(Folder folder) { - WriteVerbose("Retrieving folder properties"); + LogDebug("Retrieving folder properties"); if (AsListItem.IsPresent) { diff --git a/src/Commands/Files/GetFolderInFolder.cs b/src/Commands/Files/GetFolderInFolder.cs index f61a9a4ee..bc1558932 100644 --- a/src/Commands/Files/GetFolderInFolder.cs +++ b/src/Commands/Files/GetFolderInFolder.cs @@ -130,7 +130,7 @@ private IEnumerable GetContentsByUrl(string FolderSiteRelativeUrl) { if(ParameterSpecified(nameof(ExcludeSystemFolders))) { - WriteWarning($"The {nameof(ExcludeSystemFolders)} parameter is only supported when retrieving a specific folder. It will be ignored."); + LogWarning($"The {nameof(ExcludeSystemFolders)} parameter is only supported when retrieving a specific folder. It will be ignored."); ExcludeSystemFolders = false; } targetFolder = CurrentWeb.EnsureProperty(w => w.RootFolder); @@ -160,7 +160,7 @@ private IEnumerable GetContentsByUrl(string FolderSiteRelativeUrl) { var relativeUrl = folder.ServerRelativeUrl.Replace(CurrentWeb.ServerRelativeUrl, ""); - WriteVerbose($"Processing folder {relativeUrl}"); + LogDebug($"Processing folder {relativeUrl}"); var subFolderContents = GetContentsByUrl(relativeUrl); folderContent = folderContent.Concat(subFolderContents); diff --git a/src/Commands/Files/GetFolderItem.cs b/src/Commands/Files/GetFolderItem.cs index 3fdb466d3..b899d3391 100644 --- a/src/Commands/Files/GetFolderItem.cs +++ b/src/Commands/Files/GetFolderItem.cs @@ -197,7 +197,7 @@ private IEnumerable GetContentsByUrl(string FolderSiteRelativeUrl) { var relativeUrl = folder.ServerRelativeUrl.Replace(CurrentWeb.ServerRelativeUrl, ""); - WriteVerbose($"Processing folder {relativeUrl}"); + LogDebug($"Processing folder {relativeUrl}"); var subFolderContents = GetContentsByUrl(relativeUrl); folderContent = folderContent.Concat(subFolderContents); diff --git a/src/Commands/Files/MoveFile.cs b/src/Commands/Files/MoveFile.cs index c30ae836d..5bf740e99 100644 --- a/src/Commands/Files/MoveFile.cs +++ b/src/Commands/Files/MoveFile.cs @@ -94,16 +94,16 @@ protected override void ExecuteCmdlet() } catch (Exception ex) { - WriteVerbose($"Error occurred while trying to check if the target URL {TargetUrl} is a folder. This could happen if the target folder does not exist yet. It may still work well. Exception: {ex.Message}"); + LogDebug($"Error occurred while trying to check if the target URL {TargetUrl} is a folder. This could happen if the target folder does not exist yet. It may still work well. Exception: {ex.Message}"); } if (isFolder) { - WriteVerbose($"Moving file or folder from {sourceUri} to {targetUri}"); + LogDebug($"Moving file or folder from {sourceUri} to {targetUri}"); Move(currentContextUri, sourceUri, targetUri, SourceUrl, TargetUrl, true); } else { - WriteVerbose($"Moving file or folder from {SourceUrl} to {TargetUrl}"); + LogDebug($"Moving file or folder from {SourceUrl} to {TargetUrl}"); var file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl)); file.MoveToUsingPath(ResourcePath.FromDecodedUrl(TargetUrl), Overwrite ? MoveOperations.Overwrite : MoveOperations.None); ClientContext.ExecuteQueryRetry(); diff --git a/src/Commands/Files/ResetDocumentId.cs b/src/Commands/Files/ResetDocumentId.cs index 114c81c88..ad832d027 100644 --- a/src/Commands/Files/ResetDocumentId.cs +++ b/src/Commands/Files/ResetDocumentId.cs @@ -36,7 +36,7 @@ protected override void ExecuteCmdlet() var siteRelativeUrl = file.ServerRelativeUrl.Remove(0, new Uri(CurrentWeb.Url).AbsolutePath.Length); url = $"{CurrentWeb.Url}/_api/SP.DocumentManagement.DocumentId/ResetDocIdByServerRelativePath(decodedUrl='{siteRelativeUrl}')"; - WriteVerbose($"Making a POST request to {url} to request a new document ID for the file {file.ServerRelativeUrl}"); + LogDebug($"Making a POST request to {url} to request a new document ID for the file {file.ServerRelativeUrl}"); break; case ParameterSet_RESETLIBRARY: var library = Library.GetList(CurrentWeb, l => l.ParentWebUrl); @@ -49,7 +49,7 @@ protected override void ExecuteCmdlet() var contentType = ContentType.GetContentType(library); url = $"{CurrentWeb.Url}/_api/SP.DocumentManagement.DocumentId/ResetDocIdsInLibrary(decodedUrl='{library.RootFolder.ServerRelativeUrl.Remove(0, library.ParentWebUrl.Length)}',contentTypeId='{contentType.Id}')"; - WriteVerbose($"Making a POST request to {url} to request new document IDs for the files in library {library.Title} with content type ID {contentType.Id}"); + LogDebug($"Making a POST request to {url} to request new document IDs for the files in library {library.Title} with content type ID {contentType.Id}"); break; } diff --git a/src/Commands/Files/ResolveFolder.cs b/src/Commands/Files/ResolveFolder.cs index 70690bf5b..488aab781 100644 --- a/src/Commands/Files/ResolveFolder.cs +++ b/src/Commands/Files/ResolveFolder.cs @@ -13,7 +13,7 @@ protected override void ExecuteCmdlet() { if (MyInvocation.InvocationName.ToLower() == "ensure-pnpfolder") { - WriteWarning("Ensure-PnPFolder has been deprecated. Use Resolve-PnPFolder with the same parameters instead."); + LogWarning("Ensure-PnPFolder has been deprecated. Use Resolve-PnPFolder with the same parameters instead."); } WriteObject(CurrentWeb.EnsureFolderPath(SiteRelativePath, RetrievalExpressions)); } diff --git a/src/Commands/Files/RestoreFileVersion.cs b/src/Commands/Files/RestoreFileVersion.cs index 5d255ed5a..e927d46d4 100644 --- a/src/Commands/Files/RestoreFileVersion.cs +++ b/src/Commands/Files/RestoreFileVersion.cs @@ -34,7 +34,7 @@ protected override void ExecuteCmdlet() serverRelativeUrl = Url; } - WriteVerbose($"Looking up file at {serverRelativeUrl}"); + LogDebug($"Looking up file at {serverRelativeUrl}"); File file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl)); ClientContext.Load(file, f => f.Exists, f => f.Versions.IncludeWithDefaultProperties(i => i.CreatedBy)); @@ -42,7 +42,7 @@ protected override void ExecuteCmdlet() if (file.Exists) { - WriteVerbose($"File has been found and has {file.Versions.Count} versions"); + LogDebug($"File has been found and has {file.Versions.Count} versions"); var versions = file.Versions; @@ -50,7 +50,7 @@ protected override void ExecuteCmdlet() { if (!string.IsNullOrEmpty(Identity.Label)) { - WriteVerbose($"Trying to restore to version with label '{Identity.Label}'"); + LogDebug($"Trying to restore to version with label '{Identity.Label}'"); try { @@ -66,7 +66,7 @@ protected override void ExecuteCmdlet() } else if (Identity.Id != -1) { - WriteVerbose($"Looking up version with id '{Identity.Id}'"); + LogDebug($"Looking up version with id '{Identity.Id}'"); FileVersion version = versions.GetById(Identity.Id); ClientContext.Load(version); @@ -77,7 +77,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException($"Version with id '{Identity.Id}' does not exist", nameof(Identity)); } - WriteVerbose($"Trying to restore to version with label '{version.VersionLabel}'"); + LogDebug($"Trying to restore to version with label '{version.VersionLabel}'"); versions.RestoreByLabel(version.VersionLabel); ClientContext.ExecuteQueryRetry(); diff --git a/src/Commands/Files/SetFileRetentionLabel.cs b/src/Commands/Files/SetFileRetentionLabel.cs index 95aa93e80..d3ab7229c 100644 --- a/src/Commands/Files/SetFileRetentionLabel.cs +++ b/src/Commands/Files/SetFileRetentionLabel.cs @@ -55,12 +55,12 @@ protected override void ExecuteCmdlet() case ParameterSet_SETLABEL: if (string.IsNullOrEmpty(RetentionLabel)) { - WriteVerbose("Removing retention label"); + LogDebug("Removing retention label"); GraphRequestHelper.Delete(requestUrl); } else { - WriteVerbose($"Setting retention label to '{RetentionLabel}'"); + LogDebug($"Setting retention label to '{RetentionLabel}'"); payload = new { name = RetentionLabel diff --git a/src/Commands/Files/SetFolderPermission.cs b/src/Commands/Files/SetFolderPermission.cs index e982d7645..795059390 100644 --- a/src/Commands/Files/SetFolderPermission.cs +++ b/src/Commands/Files/SetFolderPermission.cs @@ -56,7 +56,7 @@ protected override void ExecuteCmdlet() // Ensure the folder has been found if (folder == null) { - WriteError(new ErrorRecord(new Exception("Folder not found"), "1", ErrorCategory.ObjectNotFound, null)); + LogError("Folder not found"); return; } @@ -66,7 +66,7 @@ protected override void ExecuteCmdlet() // Validate that the ListItemAllFields contains the Id which represents the ListItem ID equivallent for this folder if (folder.ListItemAllFields.ServerObjectIsNull.GetValueOrDefault(true) || folder.ListItemAllFields.Id <= 0) { - WriteError(new ErrorRecord(new Exception("ListItemId on folder not found"), "1", ErrorCategory.InvalidData, null)); + LogError("ListItemId on folder not found"); return; } @@ -156,7 +156,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new Exception("Principal not found"), "1", ErrorCategory.ObjectNotFound, null)); + LogError("Principal not found"); } } } diff --git a/src/Commands/Files/SetSiteDocumentIdPrefix.cs b/src/Commands/Files/SetSiteDocumentIdPrefix.cs index 2be8b8669..3fbd947c4 100644 --- a/src/Commands/Files/SetSiteDocumentIdPrefix.cs +++ b/src/Commands/Files/SetSiteDocumentIdPrefix.cs @@ -22,11 +22,11 @@ protected override void ExecuteCmdlet() if(!System.Text.RegularExpressions.Regex.IsMatch(DocumentIdPrefix, @"^[a-zA-Z0-9]{4,12}$")) { - WriteWarning($"{nameof(DocumentIdPrefix)} can only contain digits (0-9) and letters and must be between 4 and 12 characters in length."); + LogWarning($"{nameof(DocumentIdPrefix)} can only contain digits (0-9) and letters and must be between 4 and 12 characters in length."); } var docIdPrefixUrl = $"{CurrentWeb.Url}/_api/SP.DocumentManagement.DocumentId/SetDocIdSitePrefix(prefix='{DocumentIdPrefix}',scheduleAssignment={(ScheduleAssignment ? "true" : "false")},overwriteExistingIds={(OverwriteExistingIds ? "true" : "false")})"; - WriteVerbose($"Making a POST request to {docIdPrefixUrl} to set the document ID prefix to {DocumentIdPrefix}"); + LogDebug($"Making a POST request to {docIdPrefixUrl} to set the document ID prefix to {DocumentIdPrefix}"); RestHelper.Post(Connection.HttpClient, docIdPrefixUrl, ClientContext); } diff --git a/src/Commands/Graph/InvokeGraphMethod.cs b/src/Commands/Graph/InvokeGraphMethod.cs index 9919b2c1c..a69792f21 100644 --- a/src/Commands/Graph/InvokeGraphMethod.cs +++ b/src/Commands/Graph/InvokeGraphMethod.cs @@ -109,7 +109,7 @@ protected override void ExecuteCmdlet() } catch (Exception ex) { - WriteError(ex, ErrorCategory.WriteError); + LogError(ex); } } @@ -259,35 +259,35 @@ private void GetRequestWithPaging() private void GetRequestWithoutPaging() { - WriteVerbose($"Sending HTTP GET to {Url}"); + LogDebug($"Sending HTTP GET to {Url}"); using var response = this.GraphRequestHelper.GetResponse(Url); HandleResponse(response); } private void PostRequest() { - WriteVerbose($"Sending HTTP POST to {Url}"); + LogDebug($"Sending HTTP POST to {Url}"); var response = GraphRequestHelper.PostHttpContent(Url, GetHttpContent(), AdditionalHeaders?.GetHeaders(ConsistencyLevelEventual.IsPresent)); HandleResponse(response); } private void PutRequest() { - WriteVerbose($"Sending HTTP PUT to {Url}"); + LogDebug($"Sending HTTP PUT to {Url}"); var response = GraphRequestHelper.PutHttpContent(Url, GetHttpContent(), AdditionalHeaders?.GetHeaders(ConsistencyLevelEventual.IsPresent)); HandleResponse(response); } private void PatchRequest() { - WriteVerbose($"Sending HTTP PATCH to {Url}"); + LogDebug($"Sending HTTP PATCH to {Url}"); var response = GraphRequestHelper.Patch(GetHttpContent(), Url, AdditionalHeaders?.GetHeaders(ConsistencyLevelEventual.IsPresent)); HandleResponse(response); } private void DeleteRequest() { - WriteVerbose($"Sending HTTP DELETE to {Url}"); + LogDebug($"Sending HTTP DELETE to {Url}"); var response = GraphRequestHelper.Delete(Url, AdditionalHeaders?.GetHeaders(ConsistencyLevelEventual.IsPresent)); HandleResponse(response); } @@ -299,7 +299,7 @@ private void HandleResponse(HttpResponseMessage response) case ParameterSet_TOCONSOLE: var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); - WriteVerbose($"Returning {result.Length} characters response"); + LogDebug($"Returning {result.Length} characters response"); WriteGraphResult(result); break; @@ -307,7 +307,7 @@ private void HandleResponse(HttpResponseMessage response) case ParameterSet_TOFILE: using (var responseStreamForFile = response.Content.ReadAsStream()) { - WriteVerbose($"Writing {responseStreamForFile.Length} bytes response to {OutFile}"); + LogDebug($"Writing {responseStreamForFile.Length} bytes response to {OutFile}"); using (var fileStream = new FileStream(OutFile, FileMode.Create, FileAccess.Write)) { @@ -320,7 +320,7 @@ private void HandleResponse(HttpResponseMessage response) case ParameterSet_TOSTREAM: var responseStream = response.Content.ReadAsStream(); - WriteVerbose($"Writing {responseStream.Length} bytes response to outputstream"); + LogDebug($"Writing {responseStream.Length} bytes response to outputstream"); var memoryStream = new MemoryStream(); responseStream.CopyTo(memoryStream); diff --git a/src/Commands/Graph/RemoveAvailableSiteClassification.cs b/src/Commands/Graph/RemoveAvailableSiteClassification.cs index 265d4caa8..5b670bece 100644 --- a/src/Commands/Graph/RemoveAvailableSiteClassification.cs +++ b/src/Commands/Graph/RemoveAvailableSiteClassification.cs @@ -48,14 +48,14 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new InvalidOperationException("At least one classification is required. If you want to disable classifications, use Disable-PnPSiteClassification."), "SITECLASSIFICATIONS_ARE_REQUIRED", ErrorCategory.InvalidOperation, null)); + LogError("At least one classification is required. If you want to disable classifications, use Disable-PnPSiteClassification."); } } catch (ApplicationException ex) { if (ex.Message == @"Missing DirectorySettingTemplate for ""Group.Unified""") { - WriteError(new ErrorRecord(new InvalidOperationException("Site Classification is not enabled for this tenant"), "SITECLASSIFICATION_NOT_ENABLED", ErrorCategory.ResourceUnavailable, null)); + LogError("Site Classification is not enabled for this tenant"); } } } diff --git a/src/Commands/InformationManagement/GetLabel.cs b/src/Commands/InformationManagement/GetLabel.cs index d033c936f..caaafa6bc 100644 --- a/src/Commands/InformationManagement/GetLabel.cs +++ b/src/Commands/InformationManagement/GetLabel.cs @@ -30,7 +30,7 @@ protected override void ExecuteCmdlet() var tag = list.GetComplianceTag(); if (null == tag) { - WriteWarning("No label found for the specified list/library."); + LogWarning("No label found for the specified list/library."); } else { diff --git a/src/Commands/InformationManagement/ResetRetentionLabel.cs b/src/Commands/InformationManagement/ResetRetentionLabel.cs index e9790f5aa..26bffc583 100644 --- a/src/Commands/InformationManagement/ResetRetentionLabel.cs +++ b/src/Commands/InformationManagement/ResetRetentionLabel.cs @@ -37,12 +37,12 @@ protected override void ExecuteCmdlet() if (BatchSize > MAXBATCHSIZE) { BatchSize = MAXBATCHSIZE; - WriteVerbose($"Overriding batch size"); + LogDebug($"Overriding batch size"); } if (ItemIds == null) { - WriteWarning("No items provided"); + LogWarning("No items provided"); return; } } @@ -67,7 +67,7 @@ protected override void ExecuteCmdlet() var range = ItemIds.GetRange(0, itemsToProcess); - WriteVerbose($"Clearing retention label on batch {rangeIndex} of items"); + LogDebug($"Clearing retention label on batch {rangeIndex} of items"); Microsoft.SharePoint.Client.CompliancePolicy.SPPolicyStoreProxy.SetComplianceTagOnBulkItems(ClientContext, range, rootUrl + list.RootFolder.ServerRelativeUrl, string.Empty); ClientContext.ExecuteQueryRetry(); @@ -81,7 +81,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("List or library not found."); + LogWarning("List or library not found."); } } } diff --git a/src/Commands/InformationManagement/SetListInformationRightsManagement.cs b/src/Commands/InformationManagement/SetListInformationRightsManagement.cs index c9da05671..b5aaaaf1a 100644 --- a/src/Commands/InformationManagement/SetListInformationRightsManagement.cs +++ b/src/Commands/InformationManagement/SetListInformationRightsManagement.cs @@ -76,7 +76,7 @@ protected override void ExecuteCmdlet() if (list.IrmEnabled == false && !Enable.HasValue) { - WriteWarning("Information Rights Management is currently disabled for this list. Enable with Set-PnPListInformationRightsManagement -Enable $true"); + LogWarning("Information Rights Management is currently disabled for this list. Enable with Set-PnPListInformationRightsManagement -Enable $true"); } else { @@ -173,7 +173,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Document Access expiration is not enabled. Enable with -EnableDocumentAccessExpire $true"); + LogWarning("Document Access expiration is not enabled. Enable with -EnableDocumentAccessExpire $true"); } } @@ -184,7 +184,7 @@ protected override void ExecuteCmdlet() list.InformationRightsManagementSettings.LicenseCacheExpireDays = LicenseCacheExpireDays.Value; isDirty = true; } else { - WriteWarning("License Cache expiration is not enabled. Enable with -EnableLicenseCacheExpire $true"); + LogWarning("License Cache expiration is not enabled. Enable with -EnableLicenseCacheExpire $true"); } } @@ -196,7 +196,7 @@ protected override void ExecuteCmdlet() isDirty = true; } else { - WriteWarning("Information Rights Management (IRM) expiration is not enabled. Enable with -EnableExpiration"); + LogWarning("Information Rights Management (IRM) expiration is not enabled. Enable with -EnableExpiration"); } } diff --git a/src/Commands/InformationManagement/SetRetentionLabel.cs b/src/Commands/InformationManagement/SetRetentionLabel.cs index a8acf8dd0..425af1bc3 100644 --- a/src/Commands/InformationManagement/SetRetentionLabel.cs +++ b/src/Commands/InformationManagement/SetRetentionLabel.cs @@ -42,12 +42,12 @@ protected override void ExecuteCmdlet() if (BatchSize > MAXBATCHSIZE) { BatchSize = MAXBATCHSIZE; - WriteVerbose($"Overriding batch size"); + LogDebug($"Overriding batch size"); } if (ItemIds == null) { - WriteWarning("No items provided"); + LogWarning("No items provided"); return; } } @@ -77,7 +77,7 @@ protected override void ExecuteCmdlet() var range = ItemIds.GetRange(0, itemsToProcess); - WriteVerbose($"Setting retention label to batch {rangeIndex} of items"); + LogDebug($"Setting retention label to batch {rangeIndex} of items"); Microsoft.SharePoint.Client.CompliancePolicy.SPPolicyStoreProxy.SetComplianceTagOnBulkItems(ClientContext, range, rootUrl + list.RootFolder.ServerRelativeUrl, Label); ClientContext.ExecuteQueryRetry(); ItemIds.RemoveRange(0, itemsToProcess); @@ -90,12 +90,12 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("The provided label is not available in the site."); + LogWarning("The provided label is not available in the site."); } } else { - WriteWarning("List or library not found."); + LogWarning("List or library not found."); } } } diff --git a/src/Commands/InformationManagement/SetSiteClosure.cs b/src/Commands/InformationManagement/SetSiteClosure.cs index b7c820577..995fcb965 100644 --- a/src/Commands/InformationManagement/SetSiteClosure.cs +++ b/src/Commands/InformationManagement/SetSiteClosure.cs @@ -25,7 +25,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("No site policy applied. Set the Site Policy with Set-PnPSitePolicy and retrieve all available policies with Get-PnPSitePolicy -AllAvailable"); + LogWarning("No site policy applied. Set the Site Policy with Set-PnPSitePolicy and retrieve all available policies with Get-PnPSitePolicy -AllAvailable"); } } } diff --git a/src/Commands/ListDesign/GetListDesign.cs b/src/Commands/ListDesign/GetListDesign.cs index 1713d054c..b2fc20c6e 100644 --- a/src/Commands/ListDesign/GetListDesign.cs +++ b/src/Commands/ListDesign/GetListDesign.cs @@ -21,7 +21,7 @@ protected override void ExecuteCmdlet() if(listDesigns.Length == 0) { - WriteVerbose($"No list designs with the identity provided through {nameof(Identity)} have been found"); + LogDebug($"No list designs with the identity provided through {nameof(Identity)} have been found"); } WriteObject(listDesigns, true); diff --git a/src/Commands/ListDesign/InvokeListDesign.cs b/src/Commands/ListDesign/InvokeListDesign.cs index 57cdfa3ce..4a78f7b12 100644 --- a/src/Commands/ListDesign/InvokeListDesign.cs +++ b/src/Commands/ListDesign/InvokeListDesign.cs @@ -47,7 +47,7 @@ protected override void ExecuteCmdlet() foreach (var design in designs) { - WriteVerbose($"Invoking list design '{design.Title}' ({design.Id})"); + LogDebug($"Invoking list design '{design.Title}' ({design.Id})"); var results = tenant.ApplyListDesign(webUrl, design.Id); tenantContext.Load(results); diff --git a/src/Commands/ListDesign/RemoveListDesign.cs b/src/Commands/ListDesign/RemoveListDesign.cs index 930815c44..23d85b5dd 100644 --- a/src/Commands/ListDesign/RemoveListDesign.cs +++ b/src/Commands/ListDesign/RemoveListDesign.cs @@ -21,7 +21,7 @@ public class RemoveListDesign : PnPSharePointOnlineAdminCmdlet protected override void ExecuteCmdlet() { - WriteVerbose("Looking up list design based on the provided identity"); + LogDebug("Looking up list design based on the provided identity"); var listDesigns = Identity.GetTenantListDesign(Tenant); if(listDesigns == null || listDesigns.Length == 0) @@ -35,11 +35,11 @@ protected override void ExecuteCmdlet() { if(WhatIf.ToBool()) { - WriteVerbose($"Would remove list design with id {listDesign.Id} if {nameof(WhatIf)} was not present"); + LogDebug($"Would remove list design with id {listDesign.Id} if {nameof(WhatIf)} was not present"); } else { - WriteVerbose($"Removing list design with id {listDesign.Id}"); + LogDebug($"Removing list design with id {listDesign.Id}"); Tenant.RemoveListDesign(listDesign.Id); AdminContext.ExecuteQueryRetry(); } diff --git a/src/Commands/Lists/AddListItem.cs b/src/Commands/Lists/AddListItem.cs index df0eeffc1..721aabf81 100644 --- a/src/Commands/Lists/AddListItem.cs +++ b/src/Commands/Lists/AddListItem.cs @@ -109,7 +109,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Can not find compliance tag with value: " + Label); + LogWarning("Can not find compliance tag with value: " + Label); } } diff --git a/src/Commands/Lists/ClearDefaultColumnValues.cs b/src/Commands/Lists/ClearDefaultColumnValues.cs index bd0be0e2c..7e71e3316 100644 --- a/src/Commands/Lists/ClearDefaultColumnValues.cs +++ b/src/Commands/Lists/ClearDefaultColumnValues.cs @@ -72,7 +72,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("List is not a document library"); + LogWarning("List is not a document library"); } } } diff --git a/src/Commands/Lists/CopyList.cs b/src/Commands/Lists/CopyList.cs index 4702b295b..222e0ca09 100644 --- a/src/Commands/Lists/CopyList.cs +++ b/src/Commands/Lists/CopyList.cs @@ -49,7 +49,7 @@ protected override void ExecuteCmdlet() if(ParameterSpecified(nameof(Identity))) { // Retrieve the list to copy - WriteVerbose($"Looking up list provided through {nameof(Identity)}"); + LogDebug($"Looking up list provided through {nameof(Identity)}"); var list = Identity.GetList(ClientContext.Web); if(list == null) @@ -63,7 +63,7 @@ protected override void ExecuteCmdlet() } // Generate a site script from the list that needs to be copied - WriteVerbose($"Generating script from list at {SourceListUrl}"); + LogDebug($"Generating script from list at {SourceListUrl}"); var generatedScript = RestHelper.Post>(Connection.HttpClient, $"{Connection.Url}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.GetSiteScriptFromList()", ClientContext, new { listUrl = SourceListUrl}); // Take the site script of the list to copy @@ -72,7 +72,7 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Title)) && !string.IsNullOrWhiteSpace(Title)) { // Update the list name in the site script in the first *_listName binding parameter - WriteVerbose($"Setting list title to '{Title}'"); + LogDebug($"Setting list title to '{Title}'"); JsonNode scriptAsJson = JsonNode.Parse(script); @@ -90,12 +90,12 @@ protected override void ExecuteCmdlet() if(ParameterSpecified(nameof(WhatIf))) { - WriteVerbose($"Skipping execution of site script to site at {DestinationWebUrl} due to {nameof(WhatIf)} flag being provided"); + LogDebug($"Skipping execution of site script to site at {DestinationWebUrl} due to {nameof(WhatIf)} flag being provided"); return; } // Execute site script on destination site so the list will be created - WriteVerbose($"Executing site script to site at {DestinationWebUrl}"); + LogDebug($"Executing site script to site at {DestinationWebUrl}"); var actionResults = RestHelper.Post>(Connection.HttpClient, $"{DestinationWebUrl}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.ExecuteTemplateScript()", ClientContext, new { script = script}); // Ensure site script actions have been executed @@ -107,7 +107,7 @@ protected override void ExecuteCmdlet() // Display the results of each action in verbose foreach(var actionResult in actionResults.Items) { - WriteVerbose($"Action {actionResult.Title} {(actionResult.ErrorCode != 0 ? $"failed: {actionResult.OutcomeText}" : "succeeded")}"); + LogDebug($"Action {actionResult.Title} {(actionResult.ErrorCode != 0 ? $"failed: {actionResult.OutcomeText}" : "succeeded")}"); } // Ensure the list creation succeeded @@ -122,7 +122,7 @@ protected override void ExecuteCmdlet() // Retrieve the newly created list var newListId = actionResults.Items.ElementAt(0).TargetId; - WriteVerbose($"Retrieving newly created list hosted in {DestinationWebUrl} with ID {newListId}"); + LogDebug($"Retrieving newly created list hosted in {DestinationWebUrl} with ID {newListId}"); var createdList = destinationContext.Web.Lists.GetById(Guid.Parse(newListId)); destinationContext.Load(createdList, l => l.Id, l => l.BaseTemplate, l => l.OnQuickLaunch, l => l.DefaultViewUrl, l => l.Title, l => l.Hidden, l => l.ContentTypesEnabled, l => l.RootFolder.ServerRelativeUrl); destinationContext.ExecuteQueryRetry(); diff --git a/src/Commands/Lists/GetDefaultColumnValues.cs b/src/Commands/Lists/GetDefaultColumnValues.cs index 525819ccd..0a6a91b07 100644 --- a/src/Commands/Lists/GetDefaultColumnValues.cs +++ b/src/Commands/Lists/GetDefaultColumnValues.cs @@ -42,7 +42,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("List is not a document library"); + LogWarning("List is not a document library"); } } } diff --git a/src/Commands/Lists/GetListItemAttachment.cs b/src/Commands/Lists/GetListItemAttachment.cs index bb28ca4fd..ad5fcbf10 100644 --- a/src/Commands/Lists/GetListItemAttachment.cs +++ b/src/Commands/Lists/GetListItemAttachment.cs @@ -59,7 +59,7 @@ protected override void ExecuteCmdlet() if (attachmentFilesCollection.Length == 0) { - WriteWarning($"No attachments found for the list item provided through -{nameof(Identity)}"); + LogWarning($"No attachments found for the list item provided through -{nameof(Identity)}"); } else { @@ -70,7 +70,7 @@ protected override void ExecuteCmdlet() if (System.IO.File.Exists(fileOut) && !Force) { - WriteWarning($"File '{attachment.FileName}' exists already in the specified path. This file will be skipped. Use the -Force parameter to overwrite the file in the specified path."); + LogWarning($"File '{attachment.FileName}' exists already in the specified path. This file will be skipped. Use the -Force parameter to overwrite the file in the specified path."); } else { diff --git a/src/Commands/Lists/RemoveList.cs b/src/Commands/Lists/RemoveList.cs index a13a2be02..e2a720f7b 100644 --- a/src/Commands/Lists/RemoveList.cs +++ b/src/Commands/Lists/RemoveList.cs @@ -41,7 +41,7 @@ protected override void ExecuteCmdlet() { var operationId = list.StartRecycle(); ClientContext.ExecuteQueryRetry(); - WriteVerbose($"Large List Operation Job {operationId.Value} initiated. It may take a while for this job to complete."); + LogDebug($"Large List Operation Job {operationId.Value} initiated. It may take a while for this job to complete."); WriteObject(new RecycleBinLargeOperation { RecycleBinLargeOperationId = operationId.Value, ListId = list.Id }); } else diff --git a/src/Commands/Lists/RemoveListItemAttachment.cs b/src/Commands/Lists/RemoveListItemAttachment.cs index da5399d16..8928aee2f 100644 --- a/src/Commands/Lists/RemoveListItemAttachment.cs +++ b/src/Commands/Lists/RemoveListItemAttachment.cs @@ -61,7 +61,7 @@ protected override void ExecuteCmdlet() if(files.Length == 0) { - WriteWarning($"No attachments found on the list item that can be {removeText.ToLower()}d"); + LogWarning($"No attachments found on the list item that can be {removeText.ToLower()}d"); return; } @@ -89,7 +89,7 @@ protected override void ExecuteCmdlet() if(fileToDelete == null) { - WriteWarning($"No attachment found with the name '{FileName}'"); + LogWarning($"No attachment found with the name '{FileName}'"); } else { diff --git a/src/Commands/Lists/RemoveListItemVersion.cs b/src/Commands/Lists/RemoveListItemVersion.cs index 6ae952ce0..688bdf74a 100644 --- a/src/Commands/Lists/RemoveListItemVersion.cs +++ b/src/Commands/Lists/RemoveListItemVersion.cs @@ -61,11 +61,11 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue(string.Format(Resources.Delete0, version.VersionLabel), Resources.Confirm)) { - WriteVerbose($"Trying to remove version {Version.VersionLabel}"); + LogDebug($"Trying to remove version {Version.VersionLabel}"); version.Delete(); - WriteVerbose($"Removed version {Version.VersionLabel} of list item {item.Id} in list {list.Title}"); + LogDebug($"Removed version {Version.VersionLabel} of list item {item.Id} in list {list.Title}"); } } } diff --git a/src/Commands/Lists/RestoreListItemVersion.cs b/src/Commands/Lists/RestoreListItemVersion.cs index 83c93260a..11befd321 100644 --- a/src/Commands/Lists/RestoreListItemVersion.cs +++ b/src/Commands/Lists/RestoreListItemVersion.cs @@ -69,7 +69,7 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue(string.Format(Resources.Restore, version.VersionLabel), Resources.Confirm)) { - WriteVerbose($"Trying to restore to version with label '{version.VersionLabel}'"); + LogDebug($"Trying to restore to version with label '{version.VersionLabel}'"); var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title, f => f.Hidden, f => f.ReadOnlyField, f => f.FieldTypeKind)); @@ -116,7 +116,7 @@ protected override void ExecuteCmdlet() item.Update(); ClientContext.ExecuteQueryRetry(); - WriteVerbose($"Restored version {version.VersionLabel} of list item {item.Id} in list {list.Title}"); + LogDebug($"Restored version {version.VersionLabel} of list item {item.Id} in list {list.Title}"); } } } diff --git a/src/Commands/Lists/SetDefaultColumnValues.cs b/src/Commands/Lists/SetDefaultColumnValues.cs index 3fe432fda..a040f017a 100644 --- a/src/Commands/Lists/SetDefaultColumnValues.cs +++ b/src/Commands/Lists/SetDefaultColumnValues.cs @@ -74,7 +74,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("List is not a document library"); + LogWarning("List is not a document library"); } } } diff --git a/src/Commands/Lists/SetImageListItem.cs b/src/Commands/Lists/SetImageListItem.cs index 419bc438e..281037421 100644 --- a/src/Commands/Lists/SetImageListItem.cs +++ b/src/Commands/Lists/SetImageListItem.cs @@ -114,9 +114,9 @@ protected override void ExecuteCmdlet() var folderPath = $"/{createdList.RootFolder.Name}/Lists/{list.Id}"; // Try to create the folder - WriteVerbose("Ensuring necessary folder path for the image to be uploaded."); + LogDebug("Ensuring necessary folder path for the image to be uploaded."); folder = web.EnsureFolderPath(folderPath); - WriteVerbose("Uploading the file to be set as a thumbnail image."); + LogDebug("Uploading the file to be set as a thumbnail image."); file = folder.UploadFile(fileName, Path, true); file.EnsureProperties(fi => fi.UniqueId, fi => fi.ServerRelativePath, fi => fi.Name); diff --git a/src/Commands/Lists/SetList.cs b/src/Commands/Lists/SetList.cs index 7eab9d35b..9cdbd1165 100644 --- a/src/Commands/Lists/SetList.cs +++ b/src/Commands/Lists/SetList.cs @@ -123,7 +123,7 @@ protected override void ExecuteCmdlet() if (list is null) { - WriteWarning($"List {Identity} not found"); + LogWarning($"List {Identity} not found"); return; } @@ -389,7 +389,7 @@ protected override void ExecuteCmdlet() { if (DefaultSensitivityLabelForLibrary == null) { - WriteVerbose("Removing sensitivity label from library"); + LogDebug("Removing sensitivity label from library"); list.DefaultSensitivityLabelForLibrary = null; updateRequired = true; } @@ -397,7 +397,7 @@ protected override void ExecuteCmdlet() { if (DefaultSensitivityLabelForLibrary.LabelId.HasValue) { - WriteVerbose($"Setting provided sensitivity label id '{DefaultSensitivityLabelForLibrary.LabelId}' as the default sensitivity label for the library"); + LogDebug($"Setting provided sensitivity label id '{DefaultSensitivityLabelForLibrary.LabelId}' as the default sensitivity label for the library"); list.DefaultSensitivityLabelForLibrary = DefaultSensitivityLabelForLibrary.LabelId.ToString(); updateRequired = true; } @@ -405,7 +405,7 @@ protected override void ExecuteCmdlet() { if (!string.IsNullOrEmpty(DefaultSensitivityLabelForLibrary.LabelName)) { - WriteVerbose($"Looking up sensitivity label id by label name '{DefaultSensitivityLabelForLibrary.LabelName}'"); + LogDebug($"Looking up sensitivity label id by label name '{DefaultSensitivityLabelForLibrary.LabelName}'"); var label = DefaultSensitivityLabelForLibrary.GetLabelByNameThroughGraph(Connection,RequestHelper); if (label == null || !label.Id.HasValue) @@ -414,7 +414,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Provided sensitivity label name '{DefaultSensitivityLabelForLibrary.LabelName}' resolved to sensitivity label id '{label.Id.Value}' and will be set as the default sensitivity label for the library"); + LogDebug($"Provided sensitivity label name '{DefaultSensitivityLabelForLibrary.LabelName}' resolved to sensitivity label id '{label.Id.Value}' and will be set as the default sensitivity label for the library"); list.DefaultSensitivityLabelForLibrary = label.Id.Value.ToString(); updateRequired = true; } @@ -432,7 +432,7 @@ protected override void ExecuteCmdlet() // Is this for a list or a document library if (list.BaseType == BaseType.DocumentLibrary) { - WriteVerbose($"Configuring document library to use default open mode to be '{OpenDocumentsMode}'"); + LogDebug($"Configuring document library to use default open mode to be '{OpenDocumentsMode}'"); switch (OpenDocumentsMode) { @@ -448,7 +448,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning($"{nameof(OpenDocumentsMode)} is only supported for document libraries"); + LogWarning($"{nameof(OpenDocumentsMode)} is only supported for document libraries"); } switch (OpenDocumentsMode) diff --git a/src/Commands/Lists/SetListItem.cs b/src/Commands/Lists/SetListItem.cs index 4b2755499..9a048ba55 100644 --- a/src/Commands/Lists/SetListItem.cs +++ b/src/Commands/Lists/SetListItem.cs @@ -95,7 +95,7 @@ private void SetListItemBatched() if (!values.Any() && !Force) { - WriteWarning("No values provided. Pass -Force to update anyway."); + LogWarning("No values provided. Pass -Force to update anyway."); } else { @@ -181,7 +181,7 @@ private void SetListItemSingle() if (tag is null) { - WriteWarning("Can not find compliance tag with value: " + Label); + LogWarning("Can not find compliance tag with value: " + Label); } else { @@ -205,7 +205,7 @@ private void SetListItemSingle() } catch (System.Exception error) { - WriteWarning(error.Message.ToString()); + LogWarning(error.Message.ToString()); } } itemUpdated = true; @@ -232,7 +232,7 @@ private void SetListItemSingle() if (!itemUpdated && !Force) { - WriteWarning("No values provided. Pass -Force to update anyway."); + LogWarning("No values provided. Pass -Force to update anyway."); } else { diff --git a/src/Commands/Lists/SetListPermission.cs b/src/Commands/Lists/SetListPermission.cs index 3c54d1924..96af1c264 100644 --- a/src/Commands/Lists/SetListPermission.cs +++ b/src/Commands/Lists/SetListPermission.cs @@ -87,7 +87,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new Exception("Principal not found"), "1", ErrorCategory.ObjectNotFound, null)); + LogError(new Exception("Principal not found")); } } } diff --git a/src/Commands/Lists/SetView.cs b/src/Commands/Lists/SetView.cs index b8032617e..5b78f5000 100644 --- a/src/Commands/Lists/SetView.cs +++ b/src/Commands/Lists/SetView.cs @@ -41,18 +41,18 @@ protected override void ExecuteCmdlet() if (Identity.Id != Guid.Empty) { - WriteVerbose($"Retrieving view by Id '{Identity.Id}'"); + LogDebug($"Retrieving view by Id '{Identity.Id}'"); view = list.GetViewById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Title)) { - WriteVerbose($"Retrieving view by Title '{Identity.Title}'"); + LogDebug($"Retrieving view by Title '{Identity.Title}'"); view = list.GetViewByName(Identity.Title); } } else if (Identity.View != null) { - WriteVerbose("Using view passed through the pipeline"); + LogDebug("Using view passed through the pipeline"); view = Identity.View; } else @@ -75,7 +75,7 @@ protected override void ExecuteCmdlet() var property = view.GetType().GetProperty(key); if (property == null) { - WriteWarning($"No property '{key}' found on this view. Value will be ignored."); + LogWarning($"No property '{key}' found on this view. Value will be ignored."); } else { @@ -86,7 +86,7 @@ protected override void ExecuteCmdlet() } catch (Exception e) { - WriteWarning($"Setting property '{key}' to '{value}' failed with exception '{e.Message}'. Value will be ignored."); + LogWarning($"Setting property '{key}' to '{value}' failed with exception '{e.Message}'. Value will be ignored."); } } } diff --git a/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs b/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs index 4ea444be5..b6f66d882 100644 --- a/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs +++ b/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs @@ -21,8 +21,8 @@ protected override void ExecuteCmdlet() var owners = Microsoft365GroupsUtility.GetOwners(GraphRequestHelper, groupId); if (owners != null && owners.Any()) { - WriteWarning($"Clearing all owners is not possible as there will always have to be at least one owner. To changed the owners with new owners use Set-PnPMicrosoft365GroupOwner -Identity {groupId} -Owners \"newowner@domain.com\""); - WriteWarning($"Current owner is: {owners.First().UserPrincipalName}"); + LogWarning($"Clearing all owners is not possible as there will always have to be at least one owner. To changed the owners with new owners use Set-PnPMicrosoft365GroupOwner -Identity {groupId} -Owners \"newowner@domain.com\""); + LogWarning($"Current owner is: {owners.First().UserPrincipalName}"); } } } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs index 6128759ca..f2fa967e0 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs @@ -21,12 +21,12 @@ protected override void ExecuteCmdlet() Guid groupId; if (ParameterSpecified(nameof(Identity))) { - WriteVerbose($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); + LogDebug($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); groupId = Identity.GetGroupId(GraphRequestHelper); } else { - WriteVerbose($"Validating if the current site at {Connection.Url} has a Microsoft 365 Group behind it"); + LogDebug($"Validating if the current site at {Connection.Url} has a Microsoft 365 Group behind it"); ClientContext.Load(ClientContext.Site, s => s.GroupId); ClientContext.ExecuteQueryRetry(); @@ -38,13 +38,13 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Current site at {Connection.Url} is backed by the Microsoft 365 Group with Id {groupId}"); + LogDebug($"Current site at {Connection.Url} is backed by the Microsoft 365 Group with Id {groupId}"); } } - WriteVerbose($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); + LogDebug($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); var endpoints = GraphRequestHelper.GetResultCollection($"/beta/groups/{groupId}/endpoints"); - WriteVerbose($"{endpoints.Count()} endpoint(s) found in total"); + LogDebug($"{endpoints.Count()} endpoint(s) found in total"); WriteObject(endpoints, true); } } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs index 9dd39483c..191a22fa1 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs @@ -21,12 +21,12 @@ protected override void ExecuteCmdlet() Guid groupId; if (ParameterSpecified(nameof(Identity))) { - WriteVerbose($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); + LogDebug($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); groupId = Identity.GetGroupId(GraphRequestHelper); } else { - WriteVerbose($"Validating if the current site at {Connection.Url} has a Microsoft 365 Group behind it"); + LogDebug($"Validating if the current site at {Connection.Url} has a Microsoft 365 Group behind it"); ClientContext.Load(ClientContext.Site, s => s.GroupId); ClientContext.ExecuteQueryRetry(); @@ -38,16 +38,16 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Current site at {Connection.Url} is backed by the Microsoft 365 Group with Id {groupId}"); + LogDebug($"Current site at {Connection.Url} is backed by the Microsoft 365 Group with Id {groupId}"); } } - WriteVerbose($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); + LogDebug($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); var endpoints = GraphRequestHelper.GetResultCollection($"/beta/groups/{groupId}/endpoints"); - WriteVerbose($"{endpoints.Count()} endpoint(s) found in total"); + LogDebug($"{endpoints.Count()} endpoint(s) found in total"); var yammerEndpoint = endpoints.Where(e => e.ProviderName.Equals("Microsoft Teams", StringComparison.InvariantCultureIgnoreCase)); - WriteVerbose($"{yammerEndpoint.Count()} Teams endpoint(s) found"); + LogDebug($"{yammerEndpoint.Count()} Teams endpoint(s) found"); WriteObject(yammerEndpoint, true); } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs index d17ffdaf4..59313218f 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs @@ -21,12 +21,12 @@ protected override void ExecuteCmdlet() Guid groupId; if (ParameterSpecified(nameof(Identity))) { - WriteVerbose($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); + LogDebug($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); groupId = Identity.GetGroupId(GraphRequestHelper); } else { - WriteVerbose($"Validating if the current site at {Connection.Url} has a Microsoft 365 Group behind it"); + LogDebug($"Validating if the current site at {Connection.Url} has a Microsoft 365 Group behind it"); ClientContext.Load(ClientContext.Site, s => s.GroupId); ClientContext.ExecuteQueryRetry(); @@ -38,16 +38,16 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Current site at {Connection.Url} is backed by the Microsoft 365 Group with Id {groupId}"); + LogDebug($"Current site at {Connection.Url} is backed by the Microsoft 365 Group with Id {groupId}"); } } - WriteVerbose($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); + LogDebug($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); var endpoints = GraphRequestHelper.GetResultCollection($"/beta/groups/{groupId}/endpoints"); - WriteVerbose($"{endpoints.Count()} endpoint(s) found in total"); + LogDebug($"{endpoints.Count()} endpoint(s) found in total"); var yammerEndpoint = endpoints.Where(e => e.ProviderName.Equals("Yammer", StringComparison.InvariantCultureIgnoreCase)); - WriteVerbose($"{yammerEndpoint.Count()} Yammer endpoint(s) found"); + LogDebug($"{yammerEndpoint.Count()} Yammer endpoint(s) found"); WriteObject(yammerEndpoint, true); } diff --git a/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs index 915853d24..a82a68482 100644 --- a/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs @@ -169,7 +169,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Adding sensitivity labels in App-only context is not supported by Graph API, so it will be skipped in Group creation"); + LogWarning("Adding sensitivity labels in App-only context is not supported by Graph API, so it will be skipped in Group creation"); } } diff --git a/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs index 6188c5adb..19a4a0439 100644 --- a/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs @@ -98,7 +98,7 @@ protected override void ExecuteCmdlet() } if (changed) { - WriteVerbose("Updating Microsoft 365 Group properties in Microsoft Graph"); + LogDebug("Updating Microsoft 365 Group properties in Microsoft Graph"); group = Microsoft365GroupsUtility.Update(GraphRequestHelper, group); } @@ -106,7 +106,7 @@ protected override void ExecuteCmdlet() { if (TokenHandler.RetrieveTokenType(AccessToken) != Enums.IdType.Delegate) { - WriteWarning($"{nameof(AllowExternalSenders)} can only be used with a delegate token. You're currently connected through an application token."); + LogWarning($"{nameof(AllowExternalSenders)} can only be used with a delegate token. You're currently connected through an application token."); } group.AllowExternalSenders = AllowExternalSenders.Value; @@ -117,7 +117,7 @@ protected override void ExecuteCmdlet() { if (TokenHandler.RetrieveTokenType(AccessToken) != Enums.IdType.Delegate) { - WriteWarning($"{nameof(AllowExternalSenders)} can only be used with a delegate token. You're currently connected through an application token."); + LogWarning($"{nameof(AllowExternalSenders)} can only be used with a delegate token. You're currently connected through an application token."); } group.AutoSubscribeNewMembers = AutoSubscribeNewMembers.Value; @@ -126,7 +126,7 @@ protected override void ExecuteCmdlet() if (exchangeOnlinePropertiesChanged) { - WriteVerbose("Updating Microsoft 365 Group Exchange Online properties through Microsoft Graph"); + LogDebug("Updating Microsoft 365 Group Exchange Online properties through Microsoft Graph"); group = Microsoft365GroupsUtility.UpdateExchangeOnlineSetting(GraphRequestHelper, group.Id.Value, group); } @@ -157,7 +157,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("There is already a provisioned Team for this group. Skipping Team creation."); + LogWarning("There is already a provisioned Team for this group. Skipping Team creation."); } } @@ -187,7 +187,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Adding sensitivity labels in App-only context is not supported by Graph API, so it will be skipped in Group creation"); + LogWarning("Adding sensitivity labels in App-only context is not supported by Graph API, so it will be skipped in Group creation"); } } } diff --git a/src/Commands/Model/AccessTokenPermissionValidationResponse.cs b/src/Commands/Model/AccessTokenPermissionValidationResponse.cs index 0176b4918..92fff95d3 100644 --- a/src/Commands/Model/AccessTokenPermissionValidationResponse.cs +++ b/src/Commands/Model/AccessTokenPermissionValidationResponse.cs @@ -46,7 +46,7 @@ public class AccessTokenPermissionValidationResponse internal static AccessTokenPermissionValidationResponse[] EvaluatePermissions(Type cmdletType, string accessToken, Enums.ResourceTypeName audience, Enums.IdType tokenType) { Log.Debug("AccessTokenPermissionValidationResponse",$"Evaluating {tokenType.GetDescription()} permissions in access token for audience {audience.GetDescription()}"); - //cmdlet.WriteVerbose($"Evaluating {tokenType.GetDescription()} permissions in access token for audience {audience.GetDescription()}"); + //cmdlet.LogDebug($"Evaluating {tokenType.GetDescription()} permissions in access token for audience {audience.GetDescription()}"); // Retrieve the scopes we have in our AccessToken var scopes = TokenHandler.ReturnScopes(accessToken); diff --git a/src/Commands/Model/SPOTenant.cs b/src/Commands/Model/SPOTenant.cs index 65ecedde1..625ea3815 100644 --- a/src/Commands/Model/SPOTenant.cs +++ b/src/Commands/Model/SPOTenant.cs @@ -4,6 +4,7 @@ using Microsoft.SharePoint.Client.Administration; using Microsoft.SharePoint.Client.Sharing; using PnP.PowerShell.Commands.Attributes; +using PnP.PowerShell.Commands.Base; using System; using System.Collections.Generic; using System.Linq; @@ -317,7 +318,7 @@ public class SPOTenant #endregion - public SPOTenant(Tenant tenant, ClientContext clientContext, Cmdlet cmdlet) + public SPOTenant(Tenant tenant, ClientContext clientContext, BasePSCmdlet cmdlet) { // Loop through all properties defined in this class and load the corresponding property from the Tenant object var properties = GetType().GetProperties(); @@ -345,7 +346,7 @@ public SPOTenant(Tenant tenant, ClientContext clientContext, Cmdlet cmdlet) catch(Exception e) { failedProperties++; - cmdlet.WriteVerbose($"Property {propertyName} not loaded due to error '{e.Message}'"); + cmdlet.LogDebug($"Property {propertyName} not loaded due to error '{e.Message}'"); } } @@ -362,7 +363,7 @@ public SPOTenant(Tenant tenant, ClientContext clientContext, Cmdlet cmdlet) catch(Exception e) { failedProperties++; - cmdlet.WriteVerbose($"Property AllowFilesWithKeepLabelToBeDeletedSPO and/or AllowFilesWithKeepLabelToBeDeletedODB not loaded due to error '{e.Message}'"); + cmdlet.LogDebug($"Property AllowFilesWithKeepLabelToBeDeletedSPO and/or AllowFilesWithKeepLabelToBeDeletedODB not loaded due to error '{e.Message}'"); } // DefaultOneDriveInformationBarrierMode requires manual handling as it cannot be parsed directly from the Tenant object value @@ -373,13 +374,13 @@ public SPOTenant(Tenant tenant, ClientContext clientContext, Cmdlet cmdlet) catch(Exception e) { failedProperties++; - cmdlet.WriteVerbose($"Property DefaultOneDriveInformationBarrierMode not loaded due to error '{e.Message}'"); + cmdlet.LogDebug($"Property DefaultOneDriveInformationBarrierMode not loaded due to error '{e.Message}'"); } // If one or more properties failed to load, show a warning if(failedProperties > 0) { - cmdlet.WriteWarning($"Failed to load {(failedProperties != 1 ? $"{failedProperties} properties" : "one property")}. Use -Verbose to see the details."); + cmdlet.LogWarning($"Failed to load {(failedProperties != 1 ? $"{failedProperties} properties" : "one property")}. Use -Verbose to see the details."); } } } diff --git a/src/Commands/Model/TraceLogEntry.cs b/src/Commands/Model/TraceLogEntry.cs deleted file mode 100644 index 0aee70074..000000000 --- a/src/Commands/Model/TraceLogEntry.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace PnP.PowerShell.Model -{ - public class TraceLogEntry - { - public DateTime TimeStamp; - public string Category; - // public string Three; - public string Level; - public string Message; - // public string Six; - // public string Seven; - public TraceLogEntry(string[] values) - { - TimeStamp = DateTime.Parse(values[0].Split(" : ")[1]); - Category = values[1].Trim('[', ']'); - // Three = values[2]; - Level = values[3].Trim('[', ']'); - Message = values[4]; - // Six = values[5]; - // Seven = values[6]; - } - } -} \ No newline at end of file diff --git a/src/Commands/Navigation/AddNavigationNode.cs b/src/Commands/Navigation/AddNavigationNode.cs index 0c3a3f8fd..dddf44a04 100644 --- a/src/Commands/Navigation/AddNavigationNode.cs +++ b/src/Commands/Navigation/AddNavigationNode.cs @@ -167,7 +167,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Something went wrong while trying to set AudienceIDs or Open in new tab property"); + LogWarning("Something went wrong while trying to set AudienceIDs or Open in new tab property"); } diff --git a/src/Commands/Pages/ConvertToPage.cs b/src/Commands/Pages/ConvertToPage.cs index b546d3a97..bc02de6d0 100644 --- a/src/Commands/Pages/ConvertToPage.cs +++ b/src/Commands/Pages/ConvertToPage.cs @@ -219,7 +219,7 @@ protected override void ExecuteCmdlet() if (string.IsNullOrEmpty(this.WebPartMappingFile)) { webPartMappingModel = PageTransformator.LoadDefaultWebPartMapping(); - this.WriteVerbose("Using embedded webpartmapping file. Use Export-PnPClientSidePageMapping to get that file in case you want to base your version of the embedded version."); + this.LogDebug("Using embedded webpartmapping file. Use Export-PnPClientSidePageMapping to get that file in case you want to base your version of the embedded version."); } // Validate webpartmappingfile diff --git a/src/Commands/PeopleSettings/GetProfileCardProperty.cs b/src/Commands/PeopleSettings/GetProfileCardProperty.cs index b5f2ff0ea..533549ed6 100644 --- a/src/Commands/PeopleSettings/GetProfileCardProperty.cs +++ b/src/Commands/PeopleSettings/GetProfileCardProperty.cs @@ -18,7 +18,7 @@ public class GetProfileCardProperty : PnPGraphCmdlet protected override void ExecuteCmdlet() { - WriteVerbose("Getting access token for Microsoft Graph"); + LogDebug("Getting access token for Microsoft Graph"); var requestUrl = $"/v1.0/admin/people/profileCardProperties"; if (ParameterSpecified(nameof(PropertyName))) @@ -27,14 +27,14 @@ protected override void ExecuteCmdlet() { requestUrl += $"/{PropertyName.ToString()}"; } - WriteVerbose($"Retrieving profile card property '{PropertyName}'"); + LogDebug($"Retrieving profile card property '{PropertyName}'"); var propertyResult = GraphRequestHelper.Get(requestUrl); WriteObject(propertyResult, false); } else { - WriteVerbose("Retrieving all profile card properties"); + LogDebug("Retrieving all profile card properties"); var propertyResults = GraphRequestHelper.GetResultCollection(requestUrl); WriteObject(propertyResults, true); diff --git a/src/Commands/PeopleSettings/NewProfileCardProperty.cs b/src/Commands/PeopleSettings/NewProfileCardProperty.cs index 8829ac55a..03a1d5666 100644 --- a/src/Commands/PeopleSettings/NewProfileCardProperty.cs +++ b/src/Commands/PeopleSettings/NewProfileCardProperty.cs @@ -53,7 +53,7 @@ protected override void ExecuteCmdlet() } var jsonContent = JsonContent.Create(bodyContent); - WriteVerbose($"Payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); + LogDebug($"Payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); var graphApiUrl = $"v1.0/admin/people/profileCardProperties"; var results = GraphRequestHelper.PostHttpContent(graphApiUrl, jsonContent); diff --git a/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs b/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs index 8fa3d93c7..6f938f3e8 100644 --- a/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs +++ b/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs @@ -26,14 +26,14 @@ protected override void ExecuteCmdlet() { var appName = Identity.GetName(); - WriteVerbose($"Retrieving specific Custom Connector with the provided name '{appName}' within the environment '{environmentName}'"); + LogDebug($"Retrieving specific Custom Connector with the provided name '{appName}' within the environment '{environmentName}'"); var result = ArmRequestHelper.Get( $"{powerAppsUrl}/providers/Microsoft.PowerApps{(AsAdmin ? "/scopes/admin/environments/" + environmentName : "")}/apis/{appName}?api-version=2016-11-01&$filter=environment eq '{environmentName}' and isCustomApi eq 'True'"); WriteObject(result, false); } else { - WriteVerbose($"Retrieving all Connectors within environment '{environmentName}'"); + LogDebug($"Retrieving all Connectors within environment '{environmentName}'"); var connectors = ArmRequestHelper.GetResultCollection( $"{powerAppsUrl}/providers/Microsoft.PowerApps/apis?api-version=2016-11-01&$filter=environment eq '{environmentName}' and isCustomApi eq 'True'"); WriteObject(connectors, true); diff --git a/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs b/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs index ebc07fb1d..7eb94adeb 100644 --- a/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs +++ b/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs @@ -28,7 +28,7 @@ protected override void ExecuteCmdlet() var environments = ArmRequestHelper.GetResultCollection( $"{baseUrl}/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01"); if (ParameterSpecified(nameof(Environment))) { - WriteVerbose($"Using environment as provided '{environmentName}'"); + LogDebug($"Using environment as provided '{environmentName}'"); dynamicsScopeUrl = environments.FirstOrDefault(e => e.Properties.DisplayName.ToLower() == environmentName || e.Name.ToLower() == environmentName)?.Properties.LinkedEnvironmentMetadata.InstanceApiUrl; } else @@ -39,7 +39,7 @@ protected override void ExecuteCmdlet() throw new Exception($"No default environment found, please pass in a specific environment name using the {nameof(Environment)} parameter"); } - WriteVerbose($"Using default environment as retrieved '{environmentName}'"); + LogDebug($"Using default environment as retrieved '{environmentName}'"); } // string accessTokenForGettingSolutions = TokenHandler.GetAccessToken(this, $"{dynamicsScopeUrl}/.default", Connection); @@ -50,7 +50,7 @@ protected override void ExecuteCmdlet() { var solutionName = Name.GetName(); - WriteVerbose($"Retrieving specific solution with the provided name '{solutionName}' within the environment '{environmentName}'"); + LogDebug($"Retrieving specific solution with the provided name '{solutionName}' within the environment '{environmentName}'"); var requestUrl = dynamicsScopeUrl + "/api/data/v9.0/solutions?$filter=isvisible eq true and friendlyname eq '" + solutionName + "'&$expand=publisherid&api-version=9.1"; var solution = dynamicRequestHelper.GetResultCollection(requestUrl); @@ -58,7 +58,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Retrieving all Solutions within environment '{environmentName}'"); + LogDebug($"Retrieving all Solutions within environment '{environmentName}'"); var requestUrl = dynamicsScopeUrl + "/api/data/v9.0/solutions?$filter=isvisible eq true&$expand=publisherid($select=friendlyname)&api-version=9.1"; var solutions = dynamicRequestHelper.GetResultCollection(requestUrl); WriteObject(solutions, true); diff --git a/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs b/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs index 1ce2d5316..817cf3cd2 100644 --- a/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs +++ b/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs @@ -108,7 +108,7 @@ protected override void ExecuteCmdlet() // Errors have been reported in the export request result foreach (var error in wrapper.Errors) { - WriteVerbose($"Export failed for {appName} with error {error.Code}: {error.Message}"); + LogDebug($"Export failed for {appName} with error {error.Code}: {error.Message}"); } } } diff --git a/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs b/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs index 0ce451ffa..968778ad0 100644 --- a/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs +++ b/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs @@ -30,7 +30,7 @@ protected override void ExecuteCmdlet() { var appName = Identity.GetName(); - WriteVerbose($"Retrieving specific PowerApp with the provided name '{appName}' within the environment '{environmentName}'"); + LogDebug($"Retrieving specific PowerApp with the provided name '{appName}' within the environment '{environmentName}'"); var result = PowerAppsRequestHelper.Get($"{powerAppsUrl}/providers/Microsoft.PowerApps{(AsAdmin ? "/scopes/admin/environments/" + environmentName : "")}/apps/{appName}?api-version=2016-11-01"); @@ -38,7 +38,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Retrieving all PowerApps within environment '{environmentName}'"); + LogDebug($"Retrieving all PowerApps within environment '{environmentName}'"); var apps = PowerAppsRequestHelper.GetResultCollection($"{powerAppsUrl}/providers/Microsoft.PowerApps/apps?api-version=2016-11-01&$filter=environment eq '{environmentName}'"); WriteObject(apps, true); diff --git a/src/Commands/PowerPlatform/PowerApps/SetPowerAppByPassConsent.cs b/src/Commands/PowerPlatform/PowerApps/SetPowerAppByPassConsent.cs index 525e36d68..8b00ffdec 100644 --- a/src/Commands/PowerPlatform/PowerApps/SetPowerAppByPassConsent.cs +++ b/src/Commands/PowerPlatform/PowerApps/SetPowerAppByPassConsent.cs @@ -26,7 +26,7 @@ protected override void ExecuteCmdlet() var powerAppsUrl = PowerPlatformUtility.GetPowerAppsEndpoint(Connection.AzureEnvironment); var appName = Identity.GetName(); - WriteVerbose($"Setting specific PowerApp with the provided name '{appName}' consent within the environment '{environmentName}'"); + LogDebug($"Setting specific PowerApp with the provided name '{appName}' consent within the environment '{environmentName}'"); var postData = new { diff --git a/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs b/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs index b411b4512..1ebcdbe2f 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs @@ -39,21 +39,21 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("Flow not found.", nameof(Identity)); } - WriteVerbose("Acquiring access token for Microsoft Graph to look up user"); + LogDebug("Acquiring access token for Microsoft Graph to look up user"); var graphAccessToken = TokenHandler.GetAccessToken($"https://{Connection.GraphEndPoint}/.default", Connection); - WriteVerbose("Microsoft Graph access token acquired"); + LogDebug("Microsoft Graph access token acquired"); Model.AzureAD.User user; if (Guid.TryParse(User, out Guid identityGuid)) { - WriteVerbose("Looking up user through Microsoft Graph by user id {identityGuid}"); + LogDebug("Looking up user through Microsoft Graph by user id {identityGuid}"); user = Utilities.AzureAdUtility.GetUser(graphAccessToken, identityGuid, azureEnvironment: Connection.AzureEnvironment); } else { - WriteVerbose($"Looking up user through Microsoft Graph by user principal name {User}"); + LogDebug($"Looking up user through Microsoft Graph by user principal name {User}"); user = Utilities.AzureAdUtility.GetUser(graphAccessToken, User, azureEnvironment: Connection.AzureEnvironment); } @@ -81,7 +81,7 @@ protected override void ExecuteCmdlet() } }; - WriteVerbose($"Assigning user {Role} permissions to flow {flowName} in environment {environmentName}"); + LogDebug($"Assigning user {Role} permissions to flow {flowName} in environment {environmentName}"); string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/modifyPermissions?api-version=2016-11-01", AccessToken, payload); } diff --git a/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs index 671c06da8..d58a0f1b4 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs @@ -157,7 +157,7 @@ protected override void ExecuteCmdlet() // Errors have been reported in the export request result foreach (var error in wrapper.Errors) { - WriteVerbose($"Export failed for {flowName} with error {error.Code}: {error.Message}"); + LogDebug($"Export failed for {flowName} with error {error.Code}: {error.Message}"); } } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/GetDeletedFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/GetDeletedFlow.cs index c6421e98b..4c7e73da9 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/GetDeletedFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/GetDeletedFlow.cs @@ -23,7 +23,7 @@ protected override void ExecuteCmdlet() var environmentName = ParameterSpecified(nameof(Environment)) ? Environment.GetName() : PowerPlatformUtility.GetDefaultEnvironment(ArmRequestHelper, Connection.AzureEnvironment)?.Name; var baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - WriteVerbose($"Retrieving all Power Automate Flows within environment '{environmentName}'"); + LogDebug($"Retrieving all Power Automate Flows within environment '{environmentName}'"); var flowUrl = $"{baseUrl}/providers/Microsoft.ProcessSimple/scopes/admin/environments/{environmentName}/v2/flows?api-version=2016-11-01&include=softDeletedFlows"; var results = ArmRequestHelper.GetResultCollection(flowUrl); diff --git a/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs index 1e1151c97..fb123cc8b 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs @@ -42,7 +42,7 @@ protected override void ExecuteCmdlet() { var flowName = Identity.GetName(); - WriteVerbose($"Retrieving specific Power Automate Flow with the provided name '{flowName}' within the environment '{environmentName}'"); + LogDebug($"Retrieving specific Power Automate Flow with the provided name '{flowName}' within the environment '{environmentName}'"); var result = ArmRequestHelper.Get(baseUrl + $"/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01"); WriteObject(result, false); @@ -65,7 +65,7 @@ protected override void ExecuteCmdlet() break; } - WriteVerbose($"Retrieving all Power Automate Flows within environment '{environmentName}'{(filter != null ? $" with filter '{filter}'" : "")}"); + LogDebug($"Retrieving all Power Automate Flows within environment '{environmentName}'{(filter != null ? $" with filter '{filter}'" : "")}"); var flowUrl = $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/{(AsAdmin ? "v2" : "")}/flows?api-version=2016-11-01{(filter != null ? $"&$filter={filter}" : "")}"; var flows = ArmRequestHelper.GetResultCollection(flowUrl); @@ -76,7 +76,7 @@ protected override void ExecuteCmdlet() } catch (Exception e) { - WriteError(new ErrorRecord(new Exception("Make sure you have granted access to Azure AD App to Interact with Power Platform, To help understand the required permissions visit https://pnp.github.io/powershell/articles/determinepermissions.html#help-i-cant-figure-out-which-permissions-i-need"), e.Message, ErrorCategory.AuthenticationError, null)); + LogError($"Error: {e.Message}. Make sure you have granted access to your Entra AD App to Interact with Power Platform, To help understand the required permissions visit https://pnp.github.io/powershell/articles/determinepermissions.html#help-i-cant-figure-out-which-permissions-i-need"); } } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs index 5d88cb91b..10cd3926c 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs @@ -33,19 +33,19 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue($"Remove flow with name '{flowName}'?", Properties.Resources.Confirm)) { - WriteVerbose($"Attempting to delete Flow with name {flowName}"); + LogDebug($"Attempting to delete Flow with name {flowName}"); if (ThrowExceptionIfPowerAutomateNotFound) { try { // Had to add this because DELETE doesn't throw error if invalid Flow Id or Name is provided - WriteVerbose($"Retrieving Flow with name {flowName} in environment ${environmentName}"); + LogDebug($"Retrieving Flow with name {flowName} in environment ${environmentName}"); var result = ArmRequestHelper.Get($"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01"); if (result != null) { ArmRequestHelper.Delete($"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01"); //RestHelper.Delete(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken); - WriteVerbose($"Flow with name {flowName} deleted"); + LogDebug($"Flow with name {flowName} deleted"); } } catch @@ -56,7 +56,7 @@ protected override void ExecuteCmdlet() else { ArmRequestHelper.Delete($"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01"); - WriteVerbose($"Flow with name {flowName} deleted"); + LogDebug($"Flow with name {flowName} deleted"); } } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs index 527723dfc..97e60eed8 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs @@ -39,21 +39,21 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("Flow not found.", nameof(Identity)); } - WriteVerbose("Acquiring access token for Microsoft Graph to look up user"); + LogDebug("Acquiring access token for Microsoft Graph to look up user"); var graphAccessToken = TokenHandler.GetAccessToken($"https://{Connection.GraphEndPoint}/.default", Connection); - WriteVerbose("Microsoft Graph access token acquired"); + LogDebug("Microsoft Graph access token acquired"); Model.AzureAD.User user; if (Guid.TryParse(User, out Guid identityGuid)) { - WriteVerbose("Looking up user through Microsoft Graph by user id {identityGuid}"); + LogDebug("Looking up user through Microsoft Graph by user id {identityGuid}"); user = Utilities.AzureAdUtility.GetUser(graphAccessToken, identityGuid, azureEnvironment: Connection.AzureEnvironment); } else { - WriteVerbose($"Looking up user through Microsoft Graph by user principal name {User}"); + LogDebug($"Looking up user through Microsoft Graph by user principal name {User}"); user = Utilities.AzureAdUtility.GetUser(graphAccessToken, User, azureEnvironment: Connection.AzureEnvironment); } @@ -76,7 +76,7 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue($"Remove flow owner with id '{user.Id.Value}' from flow '{flowName}'?", Properties.Resources.Confirm)) { string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - WriteVerbose($"Removing user {user.Id.Value} permissions from flow {flowName} in environment {environmentName}"); + LogDebug($"Removing user {user.Id.Value} permissions from flow {flowName} in environment {environmentName}"); RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/modifyPermissions?api-version=2016-11-01", AccessToken, payload); } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/RestoreFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/RestoreFlow.cs index d55d924e1..8cda2da41 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/RestoreFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/RestoreFlow.cs @@ -23,12 +23,12 @@ protected override void ExecuteCmdlet() var environmentName = ParameterSpecified(nameof(Environment)) ? Environment.GetName() : PowerPlatformUtility.GetDefaultEnvironment(ArmRequestHelper, Connection.AzureEnvironment)?.Name; var flowName = Identity.GetName(); - WriteVerbose($"Restoring soft-deleted flow {flowName} from environment {environmentName}"); + LogDebug($"Restoring soft-deleted flow {flowName} from environment {environmentName}"); try { RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple/scopes/admin/environments/{environmentName}/flows/{flowName}/restore?api-version=2016-11-01", AccessToken); - WriteVerbose($"Flow with name {flowName} restored"); + LogDebug($"Flow with name {flowName} restored"); } catch(Exception ex) { diff --git a/src/Commands/Principals/GetUser.cs b/src/Commands/Principals/GetUser.cs index 6899fe9c8..6e716a641 100644 --- a/src/Commands/Principals/GetUser.cs +++ b/src/Commands/Principals/GetUser.cs @@ -98,7 +98,7 @@ protected override void ExecuteCmdlet() CurrentWeb.Context.Load(CurrentWeb, s => s.ServerRelativeUrl); CurrentWeb.Context.ExecuteQueryRetry(); - WriteWarning("Using the -WithRightsAssignedDetailed parameter will cause the script to take longer than normal because of the all enumerations that take place"); + LogWarning("Using the -WithRightsAssignedDetailed parameter will cause the script to take longer than normal because of the all enumerations that take place"); users.AddRange(GetPermissions(CurrentWeb.RoleAssignments, CurrentWeb.ServerRelativeUrl)); foreach (var user in allUsersWithPermissions) { @@ -143,7 +143,7 @@ protected override void ExecuteCmdlet() // if a list or a library has unique permissions then proceed if (list.HasUniqueRoleAssignments) { - WriteVerbose(string.Format("List found with HasUniqueRoleAssignments {0}", list.RootFolder.ServerRelativeUrl)); + LogDebug(string.Format("List found with HasUniqueRoleAssignments {0}", list.RootFolder.ServerRelativeUrl)); string url = list.RootFolder.ServerRelativeUrl; CurrentWeb.Context.Load(list.RoleAssignments, r => r.Include( @@ -158,7 +158,7 @@ protected override void ExecuteCmdlet() // if the list with unique permissions also has items, check every item which is uniquely permissioned if (list.ItemCount > 0) { - WriteVerbose(string.Format("Enumerating through all listitems of {0}", list.RootFolder.ServerRelativeUrl)); + LogDebug(string.Format("Enumerating through all listitems of {0}", list.RootFolder.ServerRelativeUrl)); CamlQuery query = CamlQuery.CreateAllItemsQuery(); var queryElement = XElement.Parse(query.ViewXml); @@ -200,16 +200,16 @@ protected override void ExecuteCmdlet() { WriteProgress(itemProgress, $"Retrieving items", itemProgressCounter++, items.Count); - WriteVerbose(string.Format("Enumerating though listitemcollections")); + LogDebug(string.Format("Enumerating though listitemcollections")); foreach (var listItem in item) { - WriteVerbose(string.Format("Enumerating though listitems")); + LogDebug(string.Format("Enumerating though listitems")); listItem.EnsureProperty(i => i.HasUniqueRoleAssignments); if (listItem.HasUniqueRoleAssignments) { string listItemUrl = listItem["FileRef"].ToString(); - WriteVerbose(string.Format("List item {0} HasUniqueRoleAssignments", listItemUrl)); + LogDebug(string.Format("List item {0} HasUniqueRoleAssignments", listItemUrl)); CurrentWeb.Context.Load(listItem.RoleAssignments, r => r.Include( ra => ra.RoleDefinitionBindings, diff --git a/src/Commands/Principals/RemoveUser.cs b/src/Commands/Principals/RemoveUser.cs index 8d393cd94..e85a4ae56 100644 --- a/src/Commands/Principals/RemoveUser.cs +++ b/src/Commands/Principals/RemoveUser.cs @@ -31,7 +31,7 @@ protected override void ExecuteCmdlet() { if (Force || ShouldContinue(string.Format(Properties.Resources.RemoveUser, user.Id, user.LoginName, user.Email), Properties.Resources.Confirm)) { - WriteVerbose($"Removing user {user.Id} {user.LoginName} {user.Email}"); + LogDebug($"Removing user {user.Id} {user.LoginName} {user.Email}"); ClientContext.Web.SiteUsers.Remove(user); ClientContext.ExecuteQueryRetry(); } diff --git a/src/Commands/Principals/UpdateUserType.cs b/src/Commands/Principals/UpdateUserType.cs index 096cb11bf..8dec536fc 100644 --- a/src/Commands/Principals/UpdateUserType.cs +++ b/src/Commands/Principals/UpdateUserType.cs @@ -19,7 +19,7 @@ protected override void ExecuteCmdlet() AdminContext.ExecuteQueryRetry(); if(sitePropertiesEnumerable.Count == 0) { - WriteWarning("User Type is already up to date."); + LogWarning("User Type is already up to date."); } else { foreach(var item in sitePropertiesEnumerable) { diff --git a/src/Commands/PriviledgedIdentityManagement/EnablePriviledgedIdentityManagement.cs b/src/Commands/PriviledgedIdentityManagement/EnablePriviledgedIdentityManagement.cs index 63f891913..6cea0b67b 100644 --- a/src/Commands/PriviledgedIdentityManagement/EnablePriviledgedIdentityManagement.cs +++ b/src/Commands/PriviledgedIdentityManagement/EnablePriviledgedIdentityManagement.cs @@ -78,7 +78,7 @@ protected override void ExecuteCmdlet() if (TokenHandler.RetrieveTokenType(AccessToken) == IdType.Delegate) { // Access token is a delegate, we're going to use the currently connected user to elevate - WriteVerbose("Currently connected user will be used to elevate the role assignment"); + LogDebug("Currently connected user will be used to elevate the role assignment"); PrincipalId = TokenHandler.RetrieveTokenUser(AccessToken); } else @@ -106,7 +106,7 @@ protected override void ExecuteCmdlet() throw new PSInvalidOperationException("No eligible role assignment found"); } - WriteVerbose($"Creating role assignment schedule request"); + LogDebug($"Creating role assignment schedule request"); var response = PriviledgedIdentityManagamentUtility.CreateRoleAssignmentScheduleRequest(GraphRequestHelper, roleEligibilitySchedule, Justification, StartAt, ExpireInHours); WriteObject(response.IsSuccessStatusCode); } diff --git a/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementEligibleAssignment.cs b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementEligibleAssignment.cs index 9cac3fdf9..ecd1f4a28 100644 --- a/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementEligibleAssignment.cs +++ b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementEligibleAssignment.cs @@ -24,13 +24,13 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteVerbose("Retrieving specific eligible role assignment"); + LogDebug("Retrieving specific eligible role assignment"); var role = Identity.GetInstance(GraphRequestHelper); WriteObject(role, false); } else { - WriteVerbose("Retrieving all eligible role assignments"); + LogDebug("Retrieving all eligible role assignments"); var roles = PriviledgedIdentityManagamentUtility.GetRoleEligibilitySchedules(GraphRequestHelper); WriteObject(roles, true); } diff --git a/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementRole.cs b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementRole.cs index 32d181289..d75d83a98 100644 --- a/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementRole.cs +++ b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementRole.cs @@ -24,13 +24,13 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteVerbose("Retrieving specific role"); + LogDebug("Retrieving specific role"); var role = Identity.GetInstance(GraphRequestHelper); WriteObject(role, false); } else { - WriteVerbose("Retrieving all roles"); + LogDebug("Retrieving all roles"); var roles = PriviledgedIdentityManagamentUtility.GetRoleDefinitions(GraphRequestHelper); WriteObject(roles, true); } diff --git a/src/Commands/Provider/SPOProxy/SPOProxyCmdletBase.cs b/src/Commands/Provider/SPOProxy/SPOProxyCmdletBase.cs index 36c6a9723..74109657e 100644 --- a/src/Commands/Provider/SPOProxy/SPOProxyCmdletBase.cs +++ b/src/Commands/Provider/SPOProxy/SPOProxyCmdletBase.cs @@ -1,8 +1,9 @@ using System.Management.Automation; +using PnP.PowerShell.Commands.Base; namespace PnP.PowerShell.Commands.Provider.SPOProxy { - public abstract class SPOProxyCmdletBase : PSCmdlet + public abstract class SPOProxyCmdletBase : BasePSCmdlet { internal string[] PsPaths { get; private set; } diff --git a/src/Commands/Provisioning/Site/AddDataRowsToSiteTemplate.cs b/src/Commands/Provisioning/Site/AddDataRowsToSiteTemplate.cs index dd1af625e..47efdf2f0 100644 --- a/src/Commands/Provisioning/Site/AddDataRowsToSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/AddDataRowsToSiteTemplate.cs @@ -64,7 +64,7 @@ protected override void ExecuteCmdlet() var template = ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); if (template == null) @@ -323,7 +323,7 @@ private string GetLoginName(Web web, int userId) catch { // If user is removed/disabled from AAD, return null - WriteWarning("User cannot be found, skipped adding field value"); + LogWarning("User cannot be found, skipped adding field value"); return null; } } diff --git a/src/Commands/Provisioning/Site/AddFileToSiteTemplate.cs b/src/Commands/Provisioning/Site/AddFileToSiteTemplate.cs index 3d8e50e62..3654ec514 100644 --- a/src/Commands/Provisioning/Site/AddFileToSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/AddFileToSiteTemplate.cs @@ -52,7 +52,7 @@ protected override void ProcessRecord() // Load the template var template = ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); if (template == null) @@ -86,7 +86,7 @@ protected override void ProcessRecord() } catch (WebException exc) { - WriteWarning($"Can't add file from url {serverRelativeUrl} : {exc}"); + LogWarning($"Can't add file from url {serverRelativeUrl} : {exc}"); } } else diff --git a/src/Commands/Provisioning/Site/AddListFoldersToSiteTemplate.cs b/src/Commands/Provisioning/Site/AddListFoldersToSiteTemplate.cs index 786589e3d..7b5557c86 100644 --- a/src/Commands/Provisioning/Site/AddListFoldersToSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/AddListFoldersToSiteTemplate.cs @@ -42,7 +42,7 @@ protected override void ExecuteCmdlet() // Load the template var template = ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); if (template == null) diff --git a/src/Commands/Provisioning/Site/ConvertFolderToSiteTemplate.cs b/src/Commands/Provisioning/Site/ConvertFolderToSiteTemplate.cs index f904962e1..551294c2d 100644 --- a/src/Commands/Provisioning/Site/ConvertFolderToSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/ConvertFolderToSiteTemplate.cs @@ -1,5 +1,6 @@ using PnP.Framework.Provisioning.Connectors.OpenXML; using PnP.Framework.Provisioning.Connectors.OpenXML.Model; +using PnP.PowerShell.Commands.Base; using System; using System.Collections.Generic; using System.IO; @@ -9,7 +10,7 @@ namespace PnP.PowerShell.Commands.Provisioning { [Cmdlet(VerbsData.Convert, "PnPFolderToSiteTemplate")] - public class ConvertFolderToSiteTemplate : PSCmdlet + public class ConvertFolderToSiteTemplate : BasePSCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Out; @@ -97,7 +98,7 @@ private byte[] CreatePnPPackageFile() Folder = folder, Content = File.ReadAllBytes(currentFile.FullName) }; - WriteVerbose("Adding file:" + currentFile.Name + " - " + folder); + LogDebug("Adding file:" + currentFile.Name + " - " + folder); info.Files.Add(fileInfo); } byte[] pack = info.PackTemplate().ToArray(); diff --git a/src/Commands/Provisioning/Site/ConvertSiteTemplateToMarkdown.cs b/src/Commands/Provisioning/Site/ConvertSiteTemplateToMarkdown.cs index 4009e2909..3565bec27 100644 --- a/src/Commands/Provisioning/Site/ConvertSiteTemplateToMarkdown.cs +++ b/src/Commands/Provisioning/Site/ConvertSiteTemplateToMarkdown.cs @@ -23,7 +23,7 @@ public class ConvertSiteTemplateToMarkdown : BasePSCmdlet public SwitchParameter Force; protected override void ExecuteCmdlet() { - WriteWarning("This cmdlet is work in progress, the markdown report will improve/grow with later releases."); + LogWarning("This cmdlet is work in progress, the markdown report will improve/grow with later releases."); if (!Path.IsPathRooted(TemplatePath)) { TemplatePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, TemplatePath); diff --git a/src/Commands/Provisioning/Site/ExportListToSiteTemplate.cs b/src/Commands/Provisioning/Site/ExportListToSiteTemplate.cs index 323d89697..ea0cbd7d7 100644 --- a/src/Commands/Provisioning/Site/ExportListToSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/ExportListToSiteTemplate.cs @@ -105,7 +105,7 @@ private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string pac { case ProvisioningMessageType.Warning: { - WriteWarning(message); + LogWarning(message); break; } case ProvisioningMessageType.Progress: diff --git a/src/Commands/Provisioning/Site/GetSiteTemplate.cs b/src/Commands/Provisioning/Site/GetSiteTemplate.cs index cd735533c..b1bbbcccd 100644 --- a/src/Commands/Provisioning/Site/GetSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/GetSiteTemplate.cs @@ -123,7 +123,7 @@ protected override void ExecuteCmdlet() } if (PersistMultiLanguageResources == false && ResourceFilePrefix != null) { - WriteWarning("In order to export resource files, also specify the PersistMultiLanguageResources switch"); + LogWarning("In order to export resource files, also specify the PersistMultiLanguageResources switch"); } if (!string.IsNullOrEmpty(Out)) { @@ -298,7 +298,7 @@ private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string pac { case ProvisioningMessageType.Warning: { - WriteWarning(message); + LogWarning(message); break; } case ProvisioningMessageType.Progress: @@ -390,7 +390,7 @@ private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string pac } else if (extension == ".md") { - WriteWarning("The generation of a markdown report is work in progress, it will improve/grow with later releases."); + LogWarning("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)) { diff --git a/src/Commands/Provisioning/Site/InvokeSiteTemplate.cs b/src/Commands/Provisioning/Site/InvokeSiteTemplate.cs index 16a3ab5e3..871de2e0a 100644 --- a/src/Commands/Provisioning/Site/InvokeSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/InvokeSiteTemplate.cs @@ -150,7 +150,7 @@ protected override void ExecuteCmdlet() if (provisioningTemplate == null) { // If we don't have the template, raise an error and exit - WriteError(new ErrorRecord(new Exception("The -Path parameter targets an invalid repository or template object."), "WRONG_PATH", ErrorCategory.SyntaxError, null)); + LogError("The -Path parameter targets an invalid repository or template object."); return; } @@ -260,7 +260,7 @@ protected override void ExecuteCmdlet() { if (!warningsShown.Contains(message)) { - WriteWarning(message); + LogWarning(message); warningsShown.Add(message); } break; diff --git a/src/Commands/Provisioning/Site/NewSiteTemplate.cs b/src/Commands/Provisioning/Site/NewSiteTemplate.cs index 4bb12aa81..21702e76a 100644 --- a/src/Commands/Provisioning/Site/NewSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/NewSiteTemplate.cs @@ -1,10 +1,11 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System.Management.Automation; namespace PnP.PowerShell.Commands.Provisioning { [Cmdlet(VerbsCommon.New, "PnPSiteTemplate")] - public class NewSiteTemplate : PSCmdlet + public class NewSiteTemplate : BasePSCmdlet { protected override void ProcessRecord() { diff --git a/src/Commands/Provisioning/Site/NewSiteTemplateFromFolder.cs b/src/Commands/Provisioning/Site/NewSiteTemplateFromFolder.cs index 5bed55737..dedf17d01 100644 --- a/src/Commands/Provisioning/Site/NewSiteTemplateFromFolder.cs +++ b/src/Commands/Provisioning/Site/NewSiteTemplateFromFolder.cs @@ -146,7 +146,7 @@ private byte[] CreatePnPPackageFile(string ctId) Folder = folder, Content = System.IO.File.ReadAllBytes(currentFile.FullName) }; - WriteVerbose("Adding file:" + currentFile.Name + " - " + folder); + LogDebug("Adding file:" + currentFile.Name + " - " + folder); info.Files.Add(fileInfo); } byte[] pack = info.PackTemplate().ToArray(); diff --git a/src/Commands/Provisioning/Site/ReadSiteTemplate.cs b/src/Commands/Provisioning/Site/ReadSiteTemplate.cs index b0b3087eb..df31d99cd 100644 --- a/src/Commands/Provisioning/Site/ReadSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/ReadSiteTemplate.cs @@ -1,4 +1,5 @@ using PnP.Framework.Provisioning.Providers; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Utilities; using System.IO; using System.Management.Automation; @@ -6,7 +7,7 @@ namespace PnP.PowerShell.Commands.Provisioning { [Cmdlet(VerbsCommunications.Read, "PnPSiteTemplate", DefaultParameterSetName = ParameterSet_PATH)] - public class ReadSiteTemplate : PSCmdlet + public class ReadSiteTemplate : BasePSCmdlet { const string ParameterSet_STREAM = "By Stream"; const string ParameterSet_PATH = "By Path"; @@ -37,7 +38,7 @@ protected override void ProcessRecord() } WriteObject(ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); })); break; } @@ -45,7 +46,7 @@ protected override void ProcessRecord() { WriteObject(ProvisioningHelper.LoadSiteTemplateFromString(Xml, TemplateProviderExtensions, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); })); break; } @@ -53,7 +54,7 @@ protected override void ProcessRecord() { WriteObject(ProvisioningHelper.LoadSiteTemplatesFromStream(Stream, TemplateProviderExtensions, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }), true); break; } diff --git a/src/Commands/Provisioning/Site/RemoveFileFromSiteTemplate.cs b/src/Commands/Provisioning/Site/RemoveFileFromSiteTemplate.cs index d1c9b3c48..aa2968edc 100644 --- a/src/Commands/Provisioning/Site/RemoveFileFromSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/RemoveFileFromSiteTemplate.cs @@ -2,6 +2,7 @@ using PnP.Framework.Provisioning.Model; using PnP.Framework.Provisioning.Providers; using PnP.Framework.Provisioning.Providers.Xml; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Utilities; using System; using System.IO; @@ -11,7 +12,7 @@ namespace PnP.PowerShell.Commands.Provisioning.Site { [Cmdlet(VerbsCommon.Remove, "PnPFileFromSiteTemplate")] - public class RemoveFileFromSiteTemplate : PSCmdlet + public class RemoveFileFromSiteTemplate : BasePSCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Path; @@ -31,7 +32,7 @@ protected override void ProcessRecord() // Load the template ProvisioningTemplate template = ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); if (template == null) diff --git a/src/Commands/Provisioning/Site/SaveSiteTemplate.cs b/src/Commands/Provisioning/Site/SaveSiteTemplate.cs index c3a1683ee..af8e8bf10 100644 --- a/src/Commands/Provisioning/Site/SaveSiteTemplate.cs +++ b/src/Commands/Provisioning/Site/SaveSiteTemplate.cs @@ -2,6 +2,7 @@ using PnP.Framework.Provisioning.Model; using PnP.Framework.Provisioning.Providers; using PnP.Framework.Provisioning.Providers.Xml; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using PnP.PowerShell.Commands.Utilities; using System; @@ -12,7 +13,7 @@ namespace PnP.PowerShell.Commands.Provisioning { [Cmdlet(VerbsData.Save, "PnPSiteTemplate")] - public class SaveSiteTemplate : PSCmdlet + public class SaveSiteTemplate : BasePSCmdlet { [Parameter(Mandatory = true, ValueFromPipeline = true)] [Alias("InputInstance")] @@ -34,7 +35,7 @@ protected override void ProcessRecord() { var templateObject = Template.GetTemplate(SessionState.Path.CurrentFileSystemLocation.Path, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); // Determine the output file name and path @@ -100,7 +101,7 @@ private void ProcessFiles(ProvisioningTemplate template, string templateFileName { var templateFile = ProvisioningHelper.LoadSiteTemplateFromFile(templateFileName, null, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); if (template.Tenant?.AppCatalog != null) { diff --git a/src/Commands/Provisioning/Tenant/AddSiteTemplate.cs b/src/Commands/Provisioning/Tenant/AddSiteTemplate.cs index ddc7afa6b..b0e56e367 100644 --- a/src/Commands/Provisioning/Tenant/AddSiteTemplate.cs +++ b/src/Commands/Provisioning/Tenant/AddSiteTemplate.cs @@ -1,4 +1,5 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System; using System.Linq; using System.Management.Automation; @@ -6,7 +7,7 @@ namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.Add, "PnPSiteTemplate")] - public class AddSiteTemplate : PSCmdlet + public class AddSiteTemplate : BasePSCmdlet { [Parameter(Mandatory = true)] public ProvisioningTemplate SiteTemplate; @@ -20,7 +21,7 @@ protected override void ProcessRecord() { TenantTemplate.Templates.Add(SiteTemplate); } else { - WriteError(new ErrorRecord(new Exception($"Template with ID {SiteTemplate.Id} already exists in template"), "DUPLICATETEMPLATE", ErrorCategory.InvalidData, SiteTemplate)); + LogError($"Template with ID {SiteTemplate.Id} already exists in template"); } } } diff --git a/src/Commands/Provisioning/Tenant/AddTenantSequence.cs b/src/Commands/Provisioning/Tenant/AddTenantSequence.cs index d2b0a362d..dd213da8e 100644 --- a/src/Commands/Provisioning/Tenant/AddTenantSequence.cs +++ b/src/Commands/Provisioning/Tenant/AddTenantSequence.cs @@ -1,4 +1,5 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System; using System.Linq; using System.Management.Automation; @@ -6,7 +7,7 @@ namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.Add, "PnPTenantSequence")] - public class AddTenantSequence : PSCmdlet + public class AddTenantSequence : BasePSCmdlet { [Parameter(Mandatory = true, ParameterSetName = ParameterAttribute.AllParameterSets)] public ProvisioningHierarchy Template; @@ -23,7 +24,7 @@ protected override void ProcessRecord() } else { - WriteError(new ErrorRecord(new Exception($"Sequence with ID {Sequence.ID} already exists in template"), "DUPLICATESEQUENCEID", ErrorCategory.InvalidData, Sequence)); + LogError($"Sequence with ID {Sequence.ID} already exists in template"); } } } diff --git a/src/Commands/Provisioning/Tenant/AddTenantSequenceSite.cs b/src/Commands/Provisioning/Tenant/AddTenantSequenceSite.cs index bc3998cd1..7cab4a86c 100644 --- a/src/Commands/Provisioning/Tenant/AddTenantSequenceSite.cs +++ b/src/Commands/Provisioning/Tenant/AddTenantSequenceSite.cs @@ -1,11 +1,12 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using System.Management.Automation; namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.Add, "PnPTenantSequenceSite")] - public class AddTenantSequenceSite : PSCmdlet + public class AddTenantSequenceSite : BasePSCmdlet { [Parameter(Mandatory = true, ValueFromPipeline = true)] public ProvisioningSitePipeBind Site; diff --git a/src/Commands/Provisioning/Tenant/AddTenantSequenceSubSite.cs b/src/Commands/Provisioning/Tenant/AddTenantSequenceSubSite.cs index bb014943d..e2e7defea 100644 --- a/src/Commands/Provisioning/Tenant/AddTenantSequenceSubSite.cs +++ b/src/Commands/Provisioning/Tenant/AddTenantSequenceSubSite.cs @@ -1,4 +1,5 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System; using System.Linq; using System.Management.Automation; @@ -7,7 +8,7 @@ namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.Add, "PnPTenantSequenceSubSite")] - public class AddTenantSequenceSubSite : PSCmdlet + public class AddTenantSequenceSubSite : BasePSCmdlet { [Parameter(Mandatory = true)] public TeamNoGroupSubSite SubSite; @@ -23,7 +24,7 @@ protected override void ProcessRecord() } else { - WriteError(new ErrorRecord(new Exception($"Site with URL {SubSite.Url} already exists in sequence"), "DUPLICATEURL", ErrorCategory.InvalidData, SubSite)); + LogError($"Site with URL {SubSite.Url} already exists in sequence"); } } } diff --git a/src/Commands/Provisioning/Tenant/GetTenantTemplate.cs b/src/Commands/Provisioning/Tenant/GetTenantTemplate.cs index 1810e7e54..b3aa474e7 100644 --- a/src/Commands/Provisioning/Tenant/GetTenantTemplate.cs +++ b/src/Commands/Provisioning/Tenant/GetTenantTemplate.cs @@ -74,7 +74,7 @@ protected override void ExecuteCmdlet() } if (Out.ToLower().EndsWith(".pnp")) { - WriteWarning("This cmdlet does not save a tenant template as a PnP file."); + LogWarning("This cmdlet does not save a tenant template as a PnP file."); } var fileInfo = new FileInfo(Out); var fileSystemConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); @@ -123,7 +123,7 @@ private ProvisioningHierarchy ExtractTemplate(ExtractConfiguration configuration { case ProvisioningMessageType.Warning: { - WriteWarning(message); + LogWarning(message); break; } case ProvisioningMessageType.Progress: diff --git a/src/Commands/Provisioning/Tenant/InvokeTenantTemplate.cs b/src/Commands/Provisioning/Tenant/InvokeTenantTemplate.cs index 30002dbae..13e0e660d 100644 --- a/src/Commands/Provisioning/Tenant/InvokeTenantTemplate.cs +++ b/src/Commands/Provisioning/Tenant/InvokeTenantTemplate.cs @@ -167,7 +167,7 @@ protected override void ExecuteCmdlet() { if (!warningsShown.Contains(message)) { - WriteWarning(message); + LogWarning(message); warningsShown.Add(message); } break; @@ -338,7 +338,7 @@ private ProvisioningHierarchy GetHierarchy() { return ProvisioningHelper.LoadTenantTemplateFromFile(Path, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); } else diff --git a/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSite.cs b/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSite.cs index 9b1c104a4..8c72a015a 100644 --- a/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSite.cs +++ b/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSite.cs @@ -1,11 +1,12 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System.Linq; using System.Management.Automation; namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.New, "PnPTenantSequenceTeamNoGroupSite")] - public class NewTenantSequenceTeamNoGroupSite : PSCmdlet + public class NewTenantSequenceTeamNoGroupSite : BasePSCmdlet { [Parameter(Mandatory = true)] public string Url; diff --git a/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSubSite.cs b/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSubSite.cs index c5fd9e0c5..71cb8d35c 100644 --- a/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSubSite.cs +++ b/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSubSite.cs @@ -1,11 +1,12 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System.Linq; using System.Management.Automation; namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.New, "PnPTenantSequenceTeamNoGroupSubSite")] - public class NewTenantSequenceTeamNoGroupSubSite : PSCmdlet + public class NewTenantSequenceTeamNoGroupSubSite : BasePSCmdlet { [Parameter(Mandatory = true)] diff --git a/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamSite.cs b/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamSite.cs index b93ffdb24..1f2e36c79 100644 --- a/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamSite.cs +++ b/src/Commands/Provisioning/Tenant/NewTenantSequenceTeamSite.cs @@ -1,11 +1,12 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System.Linq; using System.Management.Automation; namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.New, "PnPTenantSequenceTeamSite")] - public class NewTenantSequenceTeamSite : PSCmdlet + public class NewTenantSequenceTeamSite : BasePSCmdlet { [Parameter(Mandatory = true)] diff --git a/src/Commands/Provisioning/Tenant/NewTenantTemplate.cs b/src/Commands/Provisioning/Tenant/NewTenantTemplate.cs index e7d9fc70b..023f03347 100644 --- a/src/Commands/Provisioning/Tenant/NewTenantTemplate.cs +++ b/src/Commands/Provisioning/Tenant/NewTenantTemplate.cs @@ -1,10 +1,11 @@ using PnP.Framework.Provisioning.Model; +using PnP.PowerShell.Commands.Base; using System.Management.Automation; namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommon.New, "PnPTenantTemplate")] - public class NewTenantTemplate : PSCmdlet + public class NewTenantTemplate : BasePSCmdlet { [Parameter(Mandatory = false)] public string Author; @@ -20,11 +21,13 @@ public class NewTenantTemplate : PSCmdlet protected override void ProcessRecord() { - var result = new ProvisioningHierarchy(); - result.Author = Author; - result.Description = Description; - result.DisplayName = DisplayName; - result.Generator = Generator; + var result = new ProvisioningHierarchy + { + Author = Author, + Description = Description, + DisplayName = DisplayName, + Generator = Generator + }; WriteObject(result); } } diff --git a/src/Commands/Provisioning/Tenant/ReadTenantTemplate.cs b/src/Commands/Provisioning/Tenant/ReadTenantTemplate.cs index 498c9bf5a..96f28eae4 100644 --- a/src/Commands/Provisioning/Tenant/ReadTenantTemplate.cs +++ b/src/Commands/Provisioning/Tenant/ReadTenantTemplate.cs @@ -1,11 +1,12 @@ -using PnP.PowerShell.Commands.Utilities; +using PnP.PowerShell.Commands.Base; +using PnP.PowerShell.Commands.Utilities; using System.IO; using System.Management.Automation; namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsCommunications.Read, "PnPTenantTemplate", DefaultParameterSetName = ParameterSet_PATH)] - public class ReadTenantTemplate : PSCmdlet + public class ReadTenantTemplate : BasePSCmdlet { const string ParameterSet_STREAM = "By Stream"; const string ParameterSet_PATH = "By Path"; @@ -33,7 +34,7 @@ protected override void ProcessRecord() } WriteObject(ProvisioningHelper.LoadTenantTemplateFromFile(Path, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); })); break; } @@ -41,7 +42,7 @@ protected override void ProcessRecord() { WriteObject(ProvisioningHelper.LoadTenantTemplateFromString(Xml, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); })); break; } @@ -49,7 +50,7 @@ protected override void ProcessRecord() { WriteObject(ProvisioningHelper.LoadTenantTemplatesFromStream(Stream, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }), true); break; } diff --git a/src/Commands/Provisioning/Tenant/SaveTenantTemplate.cs b/src/Commands/Provisioning/Tenant/SaveTenantTemplate.cs index 545d83414..190b93e0d 100644 --- a/src/Commands/Provisioning/Tenant/SaveTenantTemplate.cs +++ b/src/Commands/Provisioning/Tenant/SaveTenantTemplate.cs @@ -1,6 +1,7 @@ using PnP.Framework.Provisioning.Connectors; using PnP.Framework.Provisioning.Model; using PnP.Framework.Provisioning.Providers.Xml; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using PnP.PowerShell.Commands.Utilities; using System; @@ -11,7 +12,7 @@ namespace PnP.PowerShell.Commands.Provisioning.Tenant { [Cmdlet(VerbsData.Save, "PnPTenantTemplate")] - public class SaveTenantTemplate : PSCmdlet + public class SaveTenantTemplate : BasePSCmdlet { [Parameter(Mandatory = true, ValueFromPipeline = true)] public ProvisioningHierarchyPipeBind Template; @@ -29,7 +30,7 @@ protected override void ProcessRecord() { var templateObject = Template.GetTemplate(SessionState.Path.CurrentFileSystemLocation.Path, (e) => { - WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null)); + LogError(e); }); // Determine the output file name and path diff --git a/src/Commands/Purview/GetAvailableSensitivityLabel.cs b/src/Commands/Purview/GetAvailableSensitivityLabel.cs index a271522b0..cdc09cf22 100644 --- a/src/Commands/Purview/GetAvailableSensitivityLabel.cs +++ b/src/Commands/Purview/GetAvailableSensitivityLabel.cs @@ -29,7 +29,7 @@ protected override void ExecuteCmdlet() if (user == null) { - WriteWarning("Provided user not found"); + LogWarning("Provided user not found"); return; } diff --git a/src/Commands/Purview/RemoveSiteSensitivityLabel.cs b/src/Commands/Purview/RemoveSiteSensitivityLabel.cs index 76d429be6..b5ea0c2ea 100644 --- a/src/Commands/Purview/RemoveSiteSensitivityLabel.cs +++ b/src/Commands/Purview/RemoveSiteSensitivityLabel.cs @@ -12,20 +12,20 @@ public class RemoveSiteSensitivityLabel : PnPSharePointCmdlet { protected override void ExecuteCmdlet() { - WriteVerbose($"Verifying if the current site at {Connection.Url} is backed by a Microsoft 365 Group"); + LogDebug($"Verifying if the current site at {Connection.Url} is backed by a Microsoft 365 Group"); ClientContext.Load(ClientContext.Site, s => s.GroupId); ClientContext.ExecuteQueryRetry(); if(ClientContext.Site.GroupId != Guid.Empty) { // Site is Microsoft 365 Group backed - WriteVerbose($"Current site at {Connection.Url} is backed by Microsoft 365 Group with Id {ClientContext.Site.GroupId}, going to try removing the label from the group"); + LogDebug($"Current site at {Connection.Url} is backed by Microsoft 365 Group with Id {ClientContext.Site.GroupId}, going to try removing the label from the group"); if(Connection.ConnectionMethod == Model.ConnectionMethod.AzureADAppOnly) { - WriteWarning("Current connection is not using a delegate token and is backed by a Microsoft 365 Group, removing the Microsoft Purview sensitivity label will likely not work. Check the documentation."); + LogWarning("Current connection is not using a delegate token and is backed by a Microsoft 365 Group, removing the Microsoft Purview sensitivity label will likely not work. Check the documentation."); } - WriteVerbose($"Trying to remove the Microsoft Purview sensitivity label from the Microsoft 365 Group with Id {ClientContext.Site.GroupId} behind the current site {Connection.Url}"); + LogDebug($"Trying to remove the Microsoft Purview sensitivity label from the Microsoft 365 Group with Id {ClientContext.Site.GroupId} behind the current site {Connection.Url}"); var stringContent = new StringContent(JsonSerializer.Serialize(new { assignedLabels = new [] { new { labelId = "" }}})); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); RequestHelper.Patch(stringContent, $"beta/groups/{ClientContext.Site.GroupId}"); @@ -33,10 +33,10 @@ protected override void ExecuteCmdlet() else { // Site does not have a Microsoft 365 Group behind it - WriteVerbose($"Current site at {Connection.Url} is not backed by a Microsoft 365 Group"); + LogDebug($"Current site at {Connection.Url} is not backed by a Microsoft 365 Group"); } - WriteVerbose($"Trying to remove the Microsoft Purview sensitivity label from the current site {Connection.Url}"); + LogDebug($"Trying to remove the Microsoft Purview sensitivity label from the current site {Connection.Url}"); ClientContext.Site.SensitivityLabelId = null; ClientContext.ExecuteQueryRetry(); } diff --git a/src/Commands/Purview/SetSiteSensitivityLabel.cs b/src/Commands/Purview/SetSiteSensitivityLabel.cs index d3f60dd94..b10070043 100644 --- a/src/Commands/Purview/SetSiteSensitivityLabel.cs +++ b/src/Commands/Purview/SetSiteSensitivityLabel.cs @@ -20,7 +20,7 @@ protected override void ExecuteCmdlet() if (!Guid.TryParse(Identity, out Guid sensitivityLabelGuid)) { // Look up the sensitivity label Guid with the provided name - WriteVerbose($"Passed in label '{Identity}' is a name, going to try to lookup its Id"); + LogDebug($"Passed in label '{Identity}' is a name, going to try to lookup its Id"); var label = RequestHelper.GetResultCollection($"/beta/{(Connection.ConnectionMethod == Model.ConnectionMethod.AzureADAppOnly ? "" : "me/")}informationProtection/policy/labels?$filter=name eq '{Identity}'"); if (label == null || label.Count() == 0) @@ -29,29 +29,29 @@ protected override void ExecuteCmdlet() } sensitivityLabelId = label.ElementAt(0).Id?.ToString(); - WriteVerbose($"Microsoft Purview label with name '{Identity}' successfully resolved to Id '{sensitivityLabelId}'"); + LogDebug($"Microsoft Purview label with name '{Identity}' successfully resolved to Id '{sensitivityLabelId}'"); } else { // Sensitivity label has been passed in by its Id, we can use it as provided - WriteVerbose($"Passed in label '{Identity} is a Guid, going to use it as is"); + LogDebug($"Passed in label '{Identity} is a Guid, going to use it as is"); sensitivityLabelId = sensitivityLabelGuid.ToString(); } - WriteVerbose($"Verifying if the current site at {Connection.Url} is backed by a Microsoft 365 Group"); + LogDebug($"Verifying if the current site at {Connection.Url} is backed by a Microsoft 365 Group"); ClientContext.Load(ClientContext.Site, s => s.GroupId); ClientContext.ExecuteQueryRetry(); if (ClientContext.Site.GroupId != Guid.Empty) { // Site is Microsoft 365 Group backed - WriteVerbose($"Current site at {Connection.Url} is backed by Microsoft 365 Group with Id {ClientContext.Site.GroupId}, going to try setting the label on the group"); + LogDebug($"Current site at {Connection.Url} is backed by Microsoft 365 Group with Id {ClientContext.Site.GroupId}, going to try setting the label on the group"); if (Connection.ConnectionMethod == Model.ConnectionMethod.AzureADAppOnly) { - WriteWarning("Current connection is not using a delegate token and is backed by a Microsoft 365 Group, setting the Microsoft Purview sensitivity label will likely not work. Check the documentation."); + LogWarning("Current connection is not using a delegate token and is backed by a Microsoft 365 Group, setting the Microsoft Purview sensitivity label will likely not work. Check the documentation."); } - WriteVerbose($"Trying to set the Microsoft 365 Group with Id {ClientContext.Site.GroupId} behind the current site {Connection.Url} to Microsoft Purview sensitivity label with Id {sensitivityLabelId}"); + LogDebug($"Trying to set the Microsoft 365 Group with Id {ClientContext.Site.GroupId} behind the current site {Connection.Url} to Microsoft Purview sensitivity label with Id {sensitivityLabelId}"); var stringContent = new StringContent(JsonSerializer.Serialize(new { assignedLabels = new[] { new { labelId = sensitivityLabelId } } })); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); RequestHelper.Patch(stringContent, $"beta/groups/{ClientContext.Site.GroupId}"); @@ -59,10 +59,10 @@ protected override void ExecuteCmdlet() else { // Site does not have a Microsoft 365 Group behind it - WriteVerbose($"Current site at {Connection.Url} is not backed by a Microsoft 365 Group"); + LogDebug($"Current site at {Connection.Url} is not backed by a Microsoft 365 Group"); } - WriteVerbose($"Trying to set the current site {Connection.Url} to Microsoft Purview sensitivity label with Id {sensitivityLabelId}"); + LogDebug($"Trying to set the current site {Connection.Url} to Microsoft Purview sensitivity label with Id {sensitivityLabelId}"); ClientContext.Site.SensitivityLabelId = sensitivityLabelId; ClientContext.ExecuteQueryRetry(); } diff --git a/src/Commands/Search/GetSearchConfiguration.cs b/src/Commands/Search/GetSearchConfiguration.cs index cb4cbdd48..9a97d7e13 100644 --- a/src/Commands/Search/GetSearchConfiguration.cs +++ b/src/Commands/Search/GetSearchConfiguration.cs @@ -179,7 +179,7 @@ private List PromotedResultsToBookmarks(string json) if (promoResult.IsVisual && ExcludeVisualPromotedResults) { - WriteWarning($"Skipping visual promoted result {bookmark.Title} ({bookmark.Url})"); + LogWarning($"Skipping visual promoted result {bookmark.Title} ({bookmark.Url})"); continue; } @@ -189,7 +189,7 @@ private List PromotedResultsToBookmarks(string json) { if (condition.Terms == null || condition.QueryConditionType != "Keyword") { - WriteWarning($"Skipping {bookmark.Title} due to no trigger conditions"); + LogWarning($"Skipping {bookmark.Title} due to no trigger conditions"); continue; } @@ -205,7 +205,7 @@ private List PromotedResultsToBookmarks(string json) } if (triggerTerms.Count == 0) { - WriteWarning($"Skipping {bookmark.Title} due to no trigger terms"); + LogWarning($"Skipping {bookmark.Title} due to no trigger terms"); continue; } diff --git a/src/Commands/Search/GetSearchCrawlLog.cs b/src/Commands/Search/GetSearchCrawlLog.cs index 99c98d05a..9567ebbbf 100644 --- a/src/Commands/Search/GetSearchCrawlLog.cs +++ b/src/Commands/Search/GetSearchCrawlLog.cs @@ -139,7 +139,7 @@ protected override void ExecuteCmdlet() } catch (Exception e) { - WriteError(new ErrorRecord(new Exception("Make sure you are granted access to the crawl log via the SharePoint search admin center at https://-admin.sharepoint.com/_layouts/15/searchadmin/crawllogreadpermission.aspx"), e.Message, ErrorCategory.AuthenticationError, null)); + LogError($"Error: {e.Message}. Make sure you are granted access to the crawl log via the SharePoint search admin center at https://-admin.sharepoint.com/_layouts/15/searchadmin/crawllogreadpermission.aspx"); } } diff --git a/src/Commands/Search/GetSearchExternalConnection.cs b/src/Commands/Search/GetSearchExternalConnection.cs index 0bbadad96..dbc524650 100644 --- a/src/Commands/Search/GetSearchExternalConnection.cs +++ b/src/Commands/Search/GetSearchExternalConnection.cs @@ -24,14 +24,14 @@ protected override void ExecuteCmdlet() { graphApiUrl += $"/{Identity}"; - WriteVerbose($"Retrieving external connection with Identity '{Identity}'"); + LogDebug($"Retrieving external connection with Identity '{Identity}'"); var externalConnectionResult = GraphRequestHelper.Get(graphApiUrl); WriteObject(externalConnectionResult, false); } else { - WriteVerbose("Retrieving all external connections"); + LogDebug("Retrieving all external connections"); var externalConnectionResults = GraphRequestHelper.GetResultCollection(graphApiUrl); WriteObject(externalConnectionResults, true); diff --git a/src/Commands/Search/GetSearchExternalItem.cs b/src/Commands/Search/GetSearchExternalItem.cs index 5879c3222..894baa8ce 100644 --- a/src/Commands/Search/GetSearchExternalItem.cs +++ b/src/Commands/Search/GetSearchExternalItem.cs @@ -59,11 +59,11 @@ protected override void ExecuteCmdlet() if (hits == null || hits.Count == 0) { - WriteVerbose($"No external items found{(ParameterSpecified(nameof(Identity)) ? $" with the identity '{Identity}'" : "")} on external connection '{externalConnectionId}'"); + LogDebug($"No external items found{(ParameterSpecified(nameof(Identity)) ? $" with the identity '{Identity}'" : "")} on external connection '{externalConnectionId}'"); return; } - WriteVerbose($"Found {hits.Count} external item{(hits.Count != 1 ? "s" : "")}{(ParameterSpecified(nameof(Identity)) ? $" with the identity '{Identity}'" : "")} on external connection '{externalConnectionId}'"); + LogDebug($"Found {hits.Count} external item{(hits.Count != 1 ? "s" : "")}{(ParameterSpecified(nameof(Identity)) ? $" with the identity '{Identity}'" : "")} on external connection '{externalConnectionId}'"); var externalItems = hits.Select(s => new Model.Graph.MicrosoftSearch.ExternalItem { diff --git a/src/Commands/Search/NewSearchExternalConnection.cs b/src/Commands/Search/NewSearchExternalConnection.cs index c49590c93..8a3e43167 100644 --- a/src/Commands/Search/NewSearchExternalConnection.cs +++ b/src/Commands/Search/NewSearchExternalConnection.cs @@ -40,7 +40,7 @@ protected override void ExecuteCmdlet() } var jsonContent = JsonContent.Create(bodyContent); - WriteVerbose($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); + LogDebug($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); var graphApiUrl = $"v1.0/external/connections"; var results = GraphRequestHelper.PostHttpContent(graphApiUrl, jsonContent); diff --git a/src/Commands/Search/RemoveSearchExternalItem.cs b/src/Commands/Search/RemoveSearchExternalItem.cs index 422edfdbe..8854e16d2 100644 --- a/src/Commands/Search/RemoveSearchExternalItem.cs +++ b/src/Commands/Search/RemoveSearchExternalItem.cs @@ -24,7 +24,7 @@ protected override void ExecuteCmdlet() try { var response = GraphRequestHelper.Delete($"beta/external/connections/{externalConnectionId}/items/{ItemId}"); - WriteVerbose($"External item with ID '{ItemId}' successfully removed from external connection '{externalConnectionId}'"); + LogDebug($"External item with ID '{ItemId}' successfully removed from external connection '{externalConnectionId}'"); } catch (PSInvalidOperationException ex) { diff --git a/src/Commands/Search/SetSearchExternalConnection.cs b/src/Commands/Search/SetSearchExternalConnection.cs index 5cda07695..40f7a7a74 100644 --- a/src/Commands/Search/SetSearchExternalConnection.cs +++ b/src/Commands/Search/SetSearchExternalConnection.cs @@ -39,7 +39,7 @@ protected override void ExecuteCmdlet() } var jsonContent = JsonContent.Create(bodyContent, null, new JsonSerializerOptions { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }); - WriteVerbose($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); + LogDebug($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); var externalConnectionId = Identity.GetExternalConnectionId(GraphRequestHelper) ?? throw new PSArgumentException("No valid external connection specified", nameof(Identity)); var graphApiUrl = $"v1.0/external/connections/{externalConnectionId}"; diff --git a/src/Commands/Search/SetSearchExternalItem.cs b/src/Commands/Search/SetSearchExternalItem.cs index 817caa9b0..4855f1587 100644 --- a/src/Commands/Search/SetSearchExternalItem.cs +++ b/src/Commands/Search/SetSearchExternalItem.cs @@ -74,27 +74,27 @@ protected override void ExecuteCmdlet() } }; - WriteVerbose($"Adding {(ParameterSpecified(nameof(GrantUsers)) ? GrantUsers.Length : 0)} Grant User ACLs"); + LogDebug($"Adding {(ParameterSpecified(nameof(GrantUsers)) ? GrantUsers.Length : 0)} Grant User ACLs"); bodyContent.Acls.AddRange(GetUserAcls(GrantUsers, Enums.SearchExternalItemAclAccessType.Grant)); - WriteVerbose($"Adding {(ParameterSpecified(nameof(DenyUsers)) ? DenyUsers.Length : 0)} Deny User ACLs"); + LogDebug($"Adding {(ParameterSpecified(nameof(DenyUsers)) ? DenyUsers.Length : 0)} Deny User ACLs"); bodyContent.Acls.AddRange(GetUserAcls(DenyUsers, Enums.SearchExternalItemAclAccessType.Deny)); - WriteVerbose($"Adding {(ParameterSpecified(nameof(GrantGroups)) ? GrantGroups.Length : 0)} Grant Group ACLs"); + LogDebug($"Adding {(ParameterSpecified(nameof(GrantGroups)) ? GrantGroups.Length : 0)} Grant Group ACLs"); bodyContent.Acls.AddRange(GetGroupAcls(GrantGroups, Enums.SearchExternalItemAclAccessType.Grant)); - WriteVerbose($"Adding {(ParameterSpecified(nameof(DenyGroups)) ? DenyGroups.Length : 0)} Deny Group ACLs"); + LogDebug($"Adding {(ParameterSpecified(nameof(DenyGroups)) ? DenyGroups.Length : 0)} Deny Group ACLs"); bodyContent.Acls.AddRange(GetGroupAcls(DenyGroups, Enums.SearchExternalItemAclAccessType.Deny)); - WriteVerbose($"Adding {(ParameterSpecified(nameof(GrantExternalGroups)) ? GrantExternalGroups.Length : 0)} Grant External Group ACLs"); + LogDebug($"Adding {(ParameterSpecified(nameof(GrantExternalGroups)) ? GrantExternalGroups.Length : 0)} Grant External Group ACLs"); bodyContent.Acls.AddRange(GetExternalGroupAcls(GrantExternalGroups, Enums.SearchExternalItemAclAccessType.Grant)); - WriteVerbose($"Adding {(ParameterSpecified(nameof(DenyExternalGroups)) ? DenyExternalGroups.Length : 0)} Deny External Group ACLs"); + LogDebug($"Adding {(ParameterSpecified(nameof(DenyExternalGroups)) ? DenyExternalGroups.Length : 0)} Deny External Group ACLs"); bodyContent.Acls.AddRange(GetExternalGroupAcls(DenyExternalGroups, Enums.SearchExternalItemAclAccessType.Deny)); if (GrantEveryone.ToBool()) { - WriteVerbose($"Adding Grant Everyone ACL"); + LogDebug($"Adding Grant Everyone ACL"); bodyContent.Acls.Add(new Model.Graph.MicrosoftSearch.ExternalItemAcl { Type = Enums.SearchExternalItemAclType.Everyone, @@ -104,7 +104,7 @@ protected override void ExecuteCmdlet() } var jsonContent = JsonContent.Create(bodyContent); - WriteVerbose($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); + LogDebug($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); var externalConnectionId = ConnectionId.GetExternalConnectionId(GraphRequestHelper) ?? throw new PSArgumentException("No valid external connection specified", nameof(ConnectionId)); var graphApiUrl = $"v1.0/external/connections/{externalConnectionId}/items/{ItemId}"; diff --git a/src/Commands/Search/SetSearchExternalSchema.cs b/src/Commands/Search/SetSearchExternalSchema.cs index d6658228f..8a14fb6ea 100644 --- a/src/Commands/Search/SetSearchExternalSchema.cs +++ b/src/Commands/Search/SetSearchExternalSchema.cs @@ -42,49 +42,49 @@ protected override void ExecuteCmdlet() switch(ParameterSetName) { case ParamSet_TextualSchema: - WriteVerbose("Parsing schema from textual representation"); + LogDebug("Parsing schema from textual representation"); break; case ParamSet_SchemaInstance: - WriteVerbose("Using provided schema instance"); + LogDebug("Using provided schema instance"); SchemaAsText = System.Text.Json.JsonSerializer.Serialize(Schema); break; } var jsonContent = new StringContent(SchemaAsText); - WriteVerbose($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); + LogDebug($"Constructed payload: {jsonContent.ReadAsStringAsync().GetAwaiter().GetResult()}"); var graphApiUrl = $"v1.0/external/connections/{externalConnectionId}/schema"; var results = GraphRequestHelper.Patch(jsonContent, graphApiUrl); - WriteVerbose("Trying to retrieve location header from response which can be used to poll for the status of the schema operation"); + LogDebug("Trying to retrieve location header from response which can be used to poll for the status of the schema operation"); if(results.Headers.TryGetValues("Location", out var location) && location.Any()) { var schemaOperationStatusUrl = location.FirstOrDefault(); - WriteVerbose("Schema update has been scheduled"); + LogDebug("Schema update has been scheduled"); if(Wait.ToBool()) { - WriteVerbose($"Waiting for schema operation to complete by polling {schemaOperationStatusUrl}"); + LogDebug($"Waiting for schema operation to complete by polling {schemaOperationStatusUrl}"); do { - WriteVerbose("Polling schema operation status"); + LogDebug("Polling schema operation status"); var schemaOperationResult = GraphRequestHelper.Get(schemaOperationStatusUrl); if(!string.IsNullOrEmpty(schemaOperationResult.Status)) { if (schemaOperationResult.Status.ToLowerInvariant() == "completed") { - WriteVerbose("Schema operation has completed"); + LogDebug("Schema operation has completed"); break; } else { - WriteVerbose($"Schema operation still in progress with status {schemaOperationResult.Status}"); + LogDebug($"Schema operation still in progress with status {schemaOperationResult.Status}"); } } - WriteVerbose($"Waiting for {OperationStatusPollingInterval.GetValueOrDefault(30)} seconds before polling again"); + LogDebug($"Waiting for {OperationStatusPollingInterval.GetValueOrDefault(30)} seconds before polling again"); Thread.Sleep(TimeSpan.FromSeconds(OperationStatusPollingInterval.GetValueOrDefault(30))); } while (true); @@ -94,7 +94,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose("No valid Location header found in response"); + LogDebug("No valid Location header found in response"); } } } diff --git a/src/Commands/Search/SubmitSearchQuery.cs b/src/Commands/Search/SubmitSearchQuery.cs index 3fdb064b8..7edaf8ca8 100644 --- a/src/Commands/Search/SubmitSearchQuery.cs +++ b/src/Commands/Search/SubmitSearchQuery.cs @@ -194,14 +194,14 @@ internal IEnumerable Run() { var waitTime = 5 * (iterator + 1); - WriteVerbose($"Search operation failed with exception {ex.Message.TrimEnd('.')}. Attempt {iterator + 1} out of {RetryCount}. Retrying in {waitTime} seconds."); + LogDebug($"Search operation failed with exception {ex.Message.TrimEnd('.')}. Attempt {iterator + 1} out of {RetryCount}. Retrying in {waitTime} seconds."); Thread.Sleep(TimeSpan.FromSeconds(waitTime)); continue; } else if (iterator == RetryCount - 1) { - WriteVerbose($"Search operation failed with exception {ex.Message.TrimEnd('.')}. Attempt {iterator + 1} out of {RetryCount}. Done retrying."); + LogDebug($"Search operation failed with exception {ex.Message.TrimEnd('.')}. Attempt {iterator + 1} out of {RetryCount}. Done retrying."); continue; } else diff --git a/src/Commands/Security/AddFileSharingInvite.cs b/src/Commands/Security/AddFileSharingInvite.cs index e87da7497..cf77d2cf0 100644 --- a/src/Commands/Security/AddFileSharingInvite.cs +++ b/src/Commands/Security/AddFileSharingInvite.cs @@ -71,7 +71,7 @@ protected override void ExecuteCmdlet() { if (Message.Length > 2000) { - WriteVerbose("Invitation message length cannot exceed 2000 characters, trimming the message"); + LogDebug("Invitation message length cannot exceed 2000 characters, trimming the message"); Message = Message.Substring(0, 2000); } } diff --git a/src/Commands/Security/AddFolderSharingInvite.cs b/src/Commands/Security/AddFolderSharingInvite.cs index e4a838a04..68f6c7be6 100644 --- a/src/Commands/Security/AddFolderSharingInvite.cs +++ b/src/Commands/Security/AddFolderSharingInvite.cs @@ -62,7 +62,7 @@ protected override void ExecuteCmdlet() { if (Message.Length > 2000) { - WriteVerbose("Invitation message length cannot exceed 2000 characters, trimming the message"); + LogDebug("Invitation message length cannot exceed 2000 characters, trimming the message"); Message = Message.Substring(0, 2000); } } diff --git a/src/Commands/Security/GetFileSharingLink.cs b/src/Commands/Security/GetFileSharingLink.cs index 58584e149..da44f16b3 100644 --- a/src/Commands/Security/GetFileSharingLink.cs +++ b/src/Commands/Security/GetFileSharingLink.cs @@ -16,7 +16,7 @@ protected override void ExecuteCmdlet() { IFile file = Identity.GetCoreFile(Connection.PnPContext, this); - WriteVerbose("Retrieving file sharing details from Microsoft Graph"); + LogDebug("Retrieving file sharing details from Microsoft Graph"); var sharingLinks = file?.GetShareLinks(); WriteObject(sharingLinks?.RequestedItems, true); diff --git a/src/Commands/ServiceHealth/GetMicrosoft365Roadmap.cs b/src/Commands/ServiceHealth/GetMicrosoft365Roadmap.cs index 08b238483..2975d1181 100644 --- a/src/Commands/ServiceHealth/GetMicrosoft365Roadmap.cs +++ b/src/Commands/ServiceHealth/GetMicrosoft365Roadmap.cs @@ -3,19 +3,20 @@ using System.Text.Json; using System.Text.Json.Serialization; using PnP.PowerShell.Commands.Model.ServiceHealth; +using PnP.PowerShell.Commands.Base; namespace PnP.PowerShell.Commands.ServiceHealth { [Cmdlet(VerbsCommon.Get, "PnPMicrosoft365Roadmap")] [OutputType(typeof(List))] - public class GetMicrosoft365Roadmap : PSCmdlet + public class GetMicrosoft365Roadmap : BasePSCmdlet { [Parameter(Mandatory = false)] public string RoadmapUrl = "https://www.microsoft.com/releasecommunications/api/v1/m365"; protected override void ProcessRecord() { - WriteVerbose($"Retrieving the Microsoft 365 Roadmap from {RoadmapUrl}"); + LogDebug($"Retrieving the Microsoft 365 Roadmap from {RoadmapUrl}"); var response = Framework.Http.PnPHttpClient.Instance.GetHttpClient().GetAsync(RoadmapUrl).GetAwaiter().GetResult(); if (!response.IsSuccessStatusCode) @@ -23,12 +24,12 @@ protected override void ProcessRecord() throw new PSInvalidOperationException($"Failed to retrieve the Microsoft 365 Roadmap from {RoadmapUrl}"); } - WriteVerbose("Successfully retrieved the Microsoft 365 Roadmap. Parsing roadmap content."); + LogDebug("Successfully retrieved the Microsoft 365 Roadmap. Parsing roadmap content."); var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); - var roadmapItems = JsonSerializer.Deserialize>(content, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); + var roadmapItems = JsonSerializer.Deserialize>(content, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); - WriteVerbose($"{roadmapItems.Count} item{(roadmapItems.Count != 1 ? "s" : "")} parsed"); + LogDebug($"{roadmapItems.Count} item{(roadmapItems.Count != 1 ? "s" : "")} parsed"); WriteObject(roadmapItems, true); } diff --git a/src/Commands/Site/AddAvailableSiteClassification.cs b/src/Commands/Site/AddAvailableSiteClassification.cs index 9a6ae8dca..d23cd2f68 100644 --- a/src/Commands/Site/AddAvailableSiteClassification.cs +++ b/src/Commands/Site/AddAvailableSiteClassification.cs @@ -34,7 +34,7 @@ protected override void ExecuteCmdlet() { if (ex.Message == @"Missing DirectorySettingTemplate for ""Group.Unified""") { - WriteError(new ErrorRecord(new InvalidOperationException("Site Classification is not enabled for this tenant"), "SITECLASSIFICATION_NOT_ENABLED", ErrorCategory.ResourceUnavailable, null)); + LogError(new InvalidOperationException("Site Classification is not enabled for this tenant")); } else { diff --git a/src/Commands/Site/AddRoleDefinition.cs b/src/Commands/Site/AddRoleDefinition.cs index 642a59350..3481ab858 100644 --- a/src/Commands/Site/AddRoleDefinition.cs +++ b/src/Commands/Site/AddRoleDefinition.cs @@ -72,7 +72,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning($"Unable to add Role Definition as there is an existing role definition with the same name. Will be skipped."); + LogWarning($"Unable to add Role Definition as there is an existing role definition with the same name. Will be skipped."); } } } diff --git a/src/Commands/Site/AddSiteCollectionAdmin.cs b/src/Commands/Site/AddSiteCollectionAdmin.cs index 093e51dbd..a84738ff4 100644 --- a/src/Commands/Site/AddSiteCollectionAdmin.cs +++ b/src/Commands/Site/AddSiteCollectionAdmin.cs @@ -33,28 +33,28 @@ protected override void ExecuteCmdlet() /// private void SetPrimarySiteCollectionAdmin() { - WriteVerbose("Retrieving details of user so it can set as the primary site collection admin"); + LogDebug("Retrieving details of user so it can set as the primary site collection admin"); User user = PrimarySiteCollectionAdmin.GetUser(ClientContext, true); if (user != null) { - WriteVerbose("User has been found, setting it as the primary site collection admin"); + LogDebug("User has been found, setting it as the primary site collection admin"); try { ClientContext.Site.Owner = user; ClientContext.ExecuteQueryRetry(); - WriteVerbose("User has been set as the primary site collection admin"); + LogDebug("User has been set as the primary site collection admin"); } catch (ServerException e) { - WriteWarning($"Exception occurred while trying to set the user as the primary site collection admin: \"{e.Message}\""); + LogWarning($"Exception occurred while trying to set the user as the primary site collection admin: \"{e.Message}\""); } } else { - WriteWarning("Unable to set user as the primary site collection admin as it wasn't found"); + LogWarning("Unable to set user as the primary site collection admin as it wasn't found"); } } @@ -63,16 +63,16 @@ private void SetPrimarySiteCollectionAdmin() /// private void AddSecondarySiteCollectionAdmins() { - WriteVerbose($"Adding {Owners.Count} users as secondary site collection admins"); + LogDebug($"Adding {Owners.Count} users as secondary site collection admins"); foreach (var owner in Owners) { - WriteVerbose("Retrieving details of user so it can be added as a secondary site collection admin"); + LogDebug("Retrieving details of user so it can be added as a secondary site collection admin"); User user = owner.GetUser(ClientContext, true); if (user != null) { - WriteVerbose("User has been found, adding it as a secondary site collection admin"); + LogDebug("User has been found, adding it as a secondary site collection admin"); user.IsSiteAdmin = true; user.Update(); @@ -81,16 +81,16 @@ private void AddSecondarySiteCollectionAdmins() { ClientContext.ExecuteQueryRetry(); - WriteVerbose("User has been added as a secondary site collection admin"); + LogDebug("User has been added as a secondary site collection admin"); } catch (ServerException e) { - WriteWarning($"Exception occurred while trying to add the user as a secondary site collection admin: \"{e.Message}\". User will be skipped."); + LogWarning($"Exception occurred while trying to add the user as a secondary site collection admin: \"{e.Message}\". User will be skipped."); } } else { - WriteWarning("Unable to add as a secondary site collectin admin as it wasn't found. User will be skipped."); + LogWarning("Unable to add as a secondary site collectin admin as it wasn't found. User will be skipped."); } } } diff --git a/src/Commands/Site/GetAvailableSiteClassification.cs b/src/Commands/Site/GetAvailableSiteClassification.cs index 9b76cea6f..8ff788d78 100644 --- a/src/Commands/Site/GetAvailableSiteClassification.cs +++ b/src/Commands/Site/GetAvailableSiteClassification.cs @@ -24,7 +24,7 @@ protected override void ExecuteCmdlet() { if (ex.Message == @"Missing DirectorySettingTemplate for ""Group.Unified""") { - WriteError(new ErrorRecord(new InvalidOperationException("Site Classification is not enabled for this tenant. Use Enable-PnPSiteClassification to enable classifications."), "SITECLASSIFICATION_NOT_ENABLED", ErrorCategory.ResourceUnavailable, null)); + LogError("Site Classification is not enabled for this tenant. Use Enable-PnPSiteClassification to enable classifications."); } else { diff --git a/src/Commands/Site/RemoveRoleDefinition.cs b/src/Commands/Site/RemoveRoleDefinition.cs index f24eece92..c08c3d518 100644 --- a/src/Commands/Site/RemoveRoleDefinition.cs +++ b/src/Commands/Site/RemoveRoleDefinition.cs @@ -25,17 +25,17 @@ protected override void ExecuteCmdlet() { roleDefinition.DeleteObject(); ClientContext.ExecuteQueryRetry(); - WriteVerbose($@"Removed Role Definition ""{roleDefinition.Name}"""); + LogDebug($@"Removed Role Definition ""{roleDefinition.Name}"""); } } catch (ServerException e) { - WriteWarning($@"Exception occurred while trying to remove the Role Definition: ""{e.Message}"". Will be skipped."); + LogWarning($@"Exception occurred while trying to remove the Role Definition: ""{e.Message}"". Will be skipped."); } } else { - WriteWarning($"Unable to remove Role Definition as it wasn't found. Will be skipped."); + LogWarning($"Unable to remove Role Definition as it wasn't found. Will be skipped."); } } } diff --git a/src/Commands/Site/RemoveSiteCollectionAdmin.cs b/src/Commands/Site/RemoveSiteCollectionAdmin.cs index f846da9c2..ef38d89d0 100644 --- a/src/Commands/Site/RemoveSiteCollectionAdmin.cs +++ b/src/Commands/Site/RemoveSiteCollectionAdmin.cs @@ -29,12 +29,12 @@ protected override void ExecuteCmdlet() } catch (ServerException e) { - WriteWarning($"Exception occurred while trying to remove the user: \"{e.Message}\". User will be skipped."); + LogWarning($"Exception occurred while trying to remove the user: \"{e.Message}\". User will be skipped."); } } else { - WriteWarning($"Unable to remove user as it wasn't found. User will be skipped."); + LogWarning($"Unable to remove user as it wasn't found. User will be skipped."); } } } diff --git a/src/Commands/Site/SetRoleDefinition.cs b/src/Commands/Site/SetRoleDefinition.cs index 326fbeb83..afa3720dd 100644 --- a/src/Commands/Site/SetRoleDefinition.cs +++ b/src/Commands/Site/SetRoleDefinition.cs @@ -42,7 +42,7 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(SelectAll)) && ParameterSpecified(nameof(ClearAll))) { - WriteWarning("Cannot SelectAll and ClearAll permissions at the same time"); + LogWarning("Cannot SelectAll and ClearAll permissions at the same time"); return; } @@ -100,7 +100,7 @@ protected override void ExecuteCmdlet() } catch (ServerException e) { - WriteWarning($@"Exception occurred while trying to set the Role Definition: ""{e.Message}"". Will be skipped."); + LogWarning($@"Exception occurred while trying to set the Role Definition: ""{e.Message}"". Will be skipped."); } } } diff --git a/src/Commands/Site/SetSite.cs b/src/Commands/Site/SetSite.cs index 2aa1b0d83..12a829bd1 100644 --- a/src/Commands/Site/SetSite.cs +++ b/src/Commands/Site/SetSite.cs @@ -188,7 +188,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning($"Unable to add Domain Name as there is an existing domain name with the same name. Will be skipped."); + LogWarning($"Unable to add Domain Name as there is an existing domain name with the same name. Will be skipped."); } } @@ -276,7 +276,7 @@ protected override void ExecuteCmdlet() if (LockState.HasValue) { tenant.SetSiteLockState(siteUrl, LockState.Value, Wait, Wait ? timeoutFunction : null); - WriteWarning("You changed the lockstate of this site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect."); + LogWarning("You changed the lockstate of this site. This change is not guaranteed to be effective immediately. Please wait a few minutes for this to take effect."); } if (Owners != null && Owners.Count > 0) { diff --git a/src/Commands/Site/SetSiteVersionPolicy.cs b/src/Commands/Site/SetSiteVersionPolicy.cs index dbecf1628..bc23c9a4b 100644 --- a/src/Commands/Site/SetSiteVersionPolicy.cs +++ b/src/Commands/Site/SetSiteVersionPolicy.cs @@ -55,7 +55,7 @@ protected override void ExecuteCmdlet() site.EnsureProperty(s => s.VersionPolicyForNewLibrariesTemplate); site.VersionPolicyForNewLibrariesTemplate.InheritTenantSettings(); context.ExecuteQueryRetry(); - WriteWarning("The setting for new document libraries takes effect immediately. Please run Get-PnPSiteVersionPolicy to display the newly set values."); + LogWarning("The setting for new document libraries takes effect immediately. Please run Get-PnPSiteVersionPolicy to display the newly set values."); } else { @@ -148,7 +148,7 @@ protected override void ExecuteCmdlet() } } - WriteWarning("The setting for new libraries takes effect immediately. Please run Get-PnPSiteVersionPolicy to display the newly set values."); + LogWarning("The setting for new libraries takes effect immediately. Please run Get-PnPSiteVersionPolicy to display the newly set values."); } if (!(ParameterSpecified(nameof(ApplyToNewDocumentLibraries)) && @@ -167,8 +167,8 @@ protected override void ExecuteCmdlet() context.ExecuteQueryRetry(); } - WriteWarning("The setting for existing libraries takes at least 24 hours to take effect. Please run Get-PnPSiteVersionPolicyStatus to check the status."); - WriteWarning("The setting for existing libraries does not trim existing versions."); + LogWarning("The setting for existing libraries takes at least 24 hours to take effect. Please run Get-PnPSiteVersionPolicyStatus to check the status."); + LogWarning("The setting for existing libraries does not trim existing versions."); } } else diff --git a/src/Commands/Site/SetTeamifyPromptHidden.cs b/src/Commands/Site/SetTeamifyPromptHidden.cs index 57436231a..5f8cabf7e 100644 --- a/src/Commands/Site/SetTeamifyPromptHidden.cs +++ b/src/Commands/Site/SetTeamifyPromptHidden.cs @@ -16,7 +16,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Teamify prompt was already hidden"); + LogWarning("Teamify prompt was already hidden"); } } } diff --git a/src/Commands/Site/UpdateAvailableSiteClassification.cs b/src/Commands/Site/UpdateAvailableSiteClassification.cs index 1d3cf8744..fbbcea9cd 100644 --- a/src/Commands/Site/UpdateAvailableSiteClassification.cs +++ b/src/Commands/Site/UpdateAvailableSiteClassification.cs @@ -76,7 +76,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new InvalidOperationException("You are trying to set the default classification to a value that is not available in the list of possible values. Use Get-PnPAvailableSiteClassification see which site classifications you can use."), "SITECLASSIFICATION_DEFAULTVALUE_INVALID", ErrorCategory.InvalidArgument, null)); + LogError("You are trying to set the default classification to a value that is not available in the list of possible values. Use Get-PnPAvailableSiteClassification see which site classifications you can use."); } } if (ParameterSpecified(nameof(UsageGuidelinesUrl))) @@ -97,7 +97,7 @@ protected override void ExecuteCmdlet() { if (ex.Message == @"Missing DirectorySettingTemplate for ""Group.Unified""") { - WriteError(new ErrorRecord(new InvalidOperationException("Site Classification is not enabled for this tenant. Use Enable-PnPSiteClassification to enable classifications."), "SITECLASSIFICATION_NOT_ENABLED", ErrorCategory.ResourceUnavailable, null)); + LogError(new InvalidOperationException("Site Classification is not enabled for this tenant. Use Enable-PnPSiteClassification to enable classifications.")); } else { diff --git a/src/Commands/SiteDesigns/GetBuiltInSiteTemplateSettings.cs b/src/Commands/SiteDesigns/GetBuiltInSiteTemplateSettings.cs index 9278832e9..7562aa0cf 100644 --- a/src/Commands/SiteDesigns/GetBuiltInSiteTemplateSettings.cs +++ b/src/Commands/SiteDesigns/GetBuiltInSiteTemplateSettings.cs @@ -41,7 +41,7 @@ protected override void ExecuteCmdlet() if(templateSetting == null || templateSetting.Value == null) { - WriteVerbose("No out of the box SharePoint site template setting with the identity provided through Identity has been found"); + LogDebug("No out of the box SharePoint site template setting with the identity provided through Identity has been found"); return; } @@ -55,12 +55,12 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose("Retrieving all out of the box SharePoint site template settings"); + LogDebug("Retrieving all out of the box SharePoint site template settings"); var templateSettings = Tenant.GetAllOutOfBoxSiteTemplateSettings(); AdminContext.ExecuteQueryRetry(); - WriteVerbose($"{templateSettings.Count} returned"); + LogDebug($"{templateSettings.Count} returned"); var responses = templateSettings.Select(ts => new BuiltInSiteTemplateSettings { diff --git a/src/Commands/SiteDesigns/GetSiteDesign.cs b/src/Commands/SiteDesigns/GetSiteDesign.cs index b3cf9c489..5c51cbe38 100644 --- a/src/Commands/SiteDesigns/GetSiteDesign.cs +++ b/src/Commands/SiteDesigns/GetSiteDesign.cs @@ -21,7 +21,7 @@ protected override void ExecuteCmdlet() if(siteDesigns == null || siteDesigns.Length == 0) { - WriteVerbose("No site designs with the identity provided through Identity have been found"); + LogDebug("No site designs with the identity provided through Identity have been found"); return; } diff --git a/src/Commands/SiteDesigns/GetSiteScriptFromList.cs b/src/Commands/SiteDesigns/GetSiteScriptFromList.cs index 05d2c9e78..9ddd85952 100644 --- a/src/Commands/SiteDesigns/GetSiteScriptFromList.cs +++ b/src/Commands/SiteDesigns/GetSiteScriptFromList.cs @@ -30,7 +30,7 @@ protected override void ExecuteCmdlet() Url = siteUrl + List.GetList(ClientContext.Web, null).RootFolder.ServerRelativeUrl; } - WriteVerbose($"Getting Site Script from list {Url}"); + LogDebug($"Getting Site Script from list {Url}"); var script = Tenant.GetSiteScriptFromList(AdminContext, Url); AdminContext.ExecuteQueryRetry(); diff --git a/src/Commands/SiteDesigns/GetSiteScriptFromWeb.cs b/src/Commands/SiteDesigns/GetSiteScriptFromWeb.cs index 1b989a16f..42baba02d 100644 --- a/src/Commands/SiteDesigns/GetSiteScriptFromWeb.cs +++ b/src/Commands/SiteDesigns/GetSiteScriptFromWeb.cs @@ -60,7 +60,7 @@ protected override void ExecuteCmdlet() Url = Connection.Url; } - WriteVerbose($"Creating site script from web {Url}"); + LogDebug($"Creating site script from web {Url}"); if (IncludeAllLists || IncludeAll) { @@ -71,10 +71,10 @@ protected override void ExecuteCmdlet() Lists = targetWebContext.Web.Lists.Select(l => System.Text.RegularExpressions.Regex.Replace(l.RootFolder.ServerRelativeUrl, @"\/(?:sites|teams)\/.*?\/", string.Empty)).ToArray(); - WriteVerbose($"Including all custom lists and libraries in the site script... {Lists.Length} found"); + LogDebug($"Including all custom lists and libraries in the site script... {Lists.Length} found"); foreach (var list in Lists) { - WriteVerbose($"- {list}"); + LogDebug($"- {list}"); } } diff --git a/src/Commands/SiteDesigns/InvokeSiteDesign.cs b/src/Commands/SiteDesigns/InvokeSiteDesign.cs index b77d3cf50..458611cdc 100644 --- a/src/Commands/SiteDesigns/InvokeSiteDesign.cs +++ b/src/Commands/SiteDesigns/InvokeSiteDesign.cs @@ -47,7 +47,7 @@ protected override void ExecuteCmdlet() foreach (var design in designs) { - WriteVerbose($"Invoking site design '{design.Title}' ({design.Id})"); + LogDebug($"Invoking site design '{design.Title}' ({design.Id})"); var results = tenant.ApplySiteDesign(webUrl, design.Id); tenantContext.Load(results); diff --git a/src/Commands/SiteDesigns/InvokeSiteScript.cs b/src/Commands/SiteDesigns/InvokeSiteScript.cs index 7cb3fcb49..a290d029d 100644 --- a/src/Commands/SiteDesigns/InvokeSiteScript.cs +++ b/src/Commands/SiteDesigns/InvokeSiteScript.cs @@ -42,7 +42,7 @@ protected override void ExecuteCmdlet() hostUrl = CurrentWeb.Url; } - WriteVerbose($"Site scripts will be applied to site {hostUrl}"); + LogDebug($"Site scripts will be applied to site {hostUrl}"); IEnumerable result = null; switch(ParameterSetName) @@ -50,11 +50,11 @@ protected override void ExecuteCmdlet() case ParameterSet_SCRIPTCONTENTS: if(ParameterSpecified(nameof(WhatIf))) { - WriteVerbose($"Provided Site Script through {nameof(Script)} will not be executed due to {nameof(WhatIf)} option being provided"); + LogDebug($"Provided Site Script through {nameof(Script)} will not be executed due to {nameof(WhatIf)} option being provided"); } else { - WriteVerbose($"Executing provided script"); + LogDebug($"Executing provided script"); result = Utilities.SiteTemplates.InvokeSiteScript(RequestHelper, Script, hostUrl).Items; } break; @@ -76,11 +76,11 @@ protected override void ExecuteCmdlet() if(ParameterSpecified(nameof(WhatIf))) { - WriteVerbose($"Site script '{script.Title}' ({script.Id}) will not be executed due to {nameof(WhatIf)} option being provided"); + LogDebug($"Site script '{script.Title}' ({script.Id}) will not be executed due to {nameof(WhatIf)} option being provided"); } else { - WriteVerbose($"Executing site script '{script.Title}' ({script.Id})"); + LogDebug($"Executing site script '{script.Title}' ({script.Id})"); result =Utilities.SiteTemplates.InvokeSiteScript(RequestHelper, script, hostUrl).Items; } } @@ -90,7 +90,7 @@ protected override void ExecuteCmdlet() // Only if there are results, show them if (result != null) { - WriteVerbose($"Site script result: {result.Count(r => r.ErrorCode == 0)} actions successful, {result.Count(r => r.ErrorCode != 0)} failed"); + LogDebug($"Site script result: {result.Count(r => r.ErrorCode == 0)} actions successful, {result.Count(r => r.ErrorCode != 0)} failed"); WriteObject(result, true); } } diff --git a/src/Commands/SiteDesigns/RemoveSiteScript.cs b/src/Commands/SiteDesigns/RemoveSiteScript.cs index 2ebe42f6f..9449e69e9 100644 --- a/src/Commands/SiteDesigns/RemoveSiteScript.cs +++ b/src/Commands/SiteDesigns/RemoveSiteScript.cs @@ -22,7 +22,7 @@ protected override void ExecuteCmdlet() { foreach(var script in Identity.GetTenantSiteScript(Tenant)) { - WriteVerbose($"Removing site script {script.Title} with id {script.Id}"); + LogDebug($"Removing site script {script.Title} with id {script.Id}"); Tenant.DeleteSiteScript(script.Id); } diff --git a/src/Commands/SiteDesigns/SetBuiltInSiteTemplateSettings.cs b/src/Commands/SiteDesigns/SetBuiltInSiteTemplateSettings.cs index 8bb246ed7..8006bee96 100644 --- a/src/Commands/SiteDesigns/SetBuiltInSiteTemplateSettings.cs +++ b/src/Commands/SiteDesigns/SetBuiltInSiteTemplateSettings.cs @@ -40,7 +40,7 @@ protected override void ExecuteCmdlet() if (!ParameterSpecified(nameof(WhatIf))) { - WriteVerbose($"Setting built in site template settings for template with Id {Identity.Id.Value} to become {(IsHidden ? "hidden" : "visible")}"); + LogDebug($"Setting built in site template settings for template with Id {Identity.Id.Value} to become {(IsHidden ? "hidden" : "visible")}"); templateSetting = Tenant.SetTenantOutOfBoxSiteTemplateSettings(new TenantOutOfBoxSiteTemplateSettings { @@ -50,7 +50,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Omitting setting built in site template settings for template with Id {Identity.Id.Value} to become {(IsHidden ? "hidden" : "visible")} as {nameof(WhatIf)} has been provided"); + LogDebug($"Omitting setting built in site template settings for template with Id {Identity.Id.Value} to become {(IsHidden ? "hidden" : "visible")} as {nameof(WhatIf)} has been provided"); } } @@ -60,7 +60,7 @@ protected override void ExecuteCmdlet() if (!ParameterSpecified(nameof(WhatIf))) { - WriteVerbose($"Setting built in site template settings for template with Id {template.Key} to become {(IsHidden ? "hidden" : "visible")}"); + LogDebug($"Setting built in site template settings for template with Id {template.Key} to become {(IsHidden ? "hidden" : "visible")}"); templateSetting = Tenant.SetTenantOutOfBoxSiteTemplateSettings(new TenantOutOfBoxSiteTemplateSettings { @@ -70,7 +70,7 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Omitting setting built in site template settings for template with Id {template.Key} to become {(IsHidden ? "hidden" : "visible")} as {nameof(WhatIf)} has been provided"); + LogDebug($"Omitting setting built in site template settings for template with Id {template.Key} to become {(IsHidden ? "hidden" : "visible")} as {nameof(WhatIf)} has been provided"); } } @@ -80,11 +80,11 @@ protected override void ExecuteCmdlet() if(templateSetting == null || templateSetting.Value == null) { - WriteVerbose("Invalid response received"); + LogDebug("Invalid response received"); return; } - WriteVerbose("Mapping response to BuiltInSiteTemplateSettings result"); + LogDebug("Mapping response to BuiltInSiteTemplateSettings result"); var response = new BuiltInSiteTemplateSettings { diff --git a/src/Commands/SiteDesigns/SetSiteDesign.cs b/src/Commands/SiteDesigns/SetSiteDesign.cs index 630352d7f..ca97a57da 100644 --- a/src/Commands/SiteDesigns/SetSiteDesign.cs +++ b/src/Commands/SiteDesigns/SetSiteDesign.cs @@ -113,7 +113,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new ItemNotFoundException(), "SITEDESIGNNOTFOUND", ErrorCategory.ObjectNotFound, Identity)); + LogError(new ItemNotFoundException()); } } } diff --git a/src/Commands/SiteDesigns/UpdateSiteDesignFromWeb.cs b/src/Commands/SiteDesigns/UpdateSiteDesignFromWeb.cs index ef9062c16..b6b8d9d99 100644 --- a/src/Commands/SiteDesigns/UpdateSiteDesignFromWeb.cs +++ b/src/Commands/SiteDesigns/UpdateSiteDesignFromWeb.cs @@ -70,7 +70,7 @@ protected override void ExecuteCmdlet() var siteDesign = siteDesigns[0]; // Generate site script - WriteVerbose($"Generating site script from {Url}"); + LogDebug($"Generating site script from {Url}"); var tenantSiteScriptSerializationInfo = new TenantSiteScriptSerializationInfo { @@ -96,12 +96,12 @@ protected override void ExecuteCmdlet() if (siteDesign.SiteScriptIds.Length > 1) { // Multiple site scripts in the site design - WriteVerbose($"Site design provided through the Identity parameter contains {siteDesign.SiteScriptIds.Length} site scripts. The first one will be overwritten with a new template from the site."); + LogDebug($"Site design provided through the Identity parameter contains {siteDesign.SiteScriptIds.Length} site scripts. The first one will be overwritten with a new template from the site."); } else { // One site script exists in the site design, which is the expected scenario - WriteVerbose($"Site design provided through the Identity parameter contains {siteDesign.SiteScriptIds.Length} site script. It will be overwritten with a new template from the site."); + LogDebug($"Site design provided through the Identity parameter contains {siteDesign.SiteScriptIds.Length} site script. It will be overwritten with a new template from the site."); } // Update an existing site script @@ -115,14 +115,14 @@ protected override void ExecuteCmdlet() catch(Microsoft.SharePoint.Client.ServerException e) when (e.ServerErrorTypeName == "System.IO.FileNotFoundException") { // Thrown when a site script is still referenced in the site design, but the actual site script has been removed. This likely means the site design is now in an orphaned state and cannot be used anymore. Going to try anyway. - WriteVerbose($"Site design provided through the Identity parameter contains a reference to site script {siteDesign.SiteScriptIds.First()} which no longer exists. Will try to add it as a new site script but it likely will fail as the site design is now orphaned. Remove the site design and create a new one if it keeps failing."); + LogDebug($"Site design provided through the Identity parameter contains a reference to site script {siteDesign.SiteScriptIds.First()} which no longer exists. Will try to add it as a new site script but it likely will fail as the site design is now orphaned. Remove the site design and create a new one if it keeps failing."); addAsNewSiteScript = true; } } else { // No site scripts in the site design - WriteVerbose($"Site design provided through the Identity parameter does not contain any site scripts yet. Adding a new site script to the site design."); + LogDebug($"Site design provided through the Identity parameter does not contain any site scripts yet. Adding a new site script to the site design."); addAsNewSiteScript = true; } diff --git a/src/Commands/Syntex/GetSyntexModel.cs b/src/Commands/Syntex/GetSyntexModel.cs index 3321fcaf8..cfbdd8022 100644 --- a/src/Commands/Syntex/GetSyntexModel.cs +++ b/src/Commands/Syntex/GetSyntexModel.cs @@ -46,7 +46,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("The connected site is not a Syntex Content Center site"); + LogWarning("The connected site is not a Syntex Content Center site"); } } } diff --git a/src/Commands/Syntex/GetSyntexModelPublication.cs b/src/Commands/Syntex/GetSyntexModelPublication.cs index 06c741bdd..36b3cccc6 100644 --- a/src/Commands/Syntex/GetSyntexModelPublication.cs +++ b/src/Commands/Syntex/GetSyntexModelPublication.cs @@ -45,7 +45,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("The connected site is not a Syntex Content Center site"); + LogWarning("The connected site is not a Syntex Content Center site"); } } } diff --git a/src/Commands/Syntex/PublishSyntexModel.cs b/src/Commands/Syntex/PublishSyntexModel.cs index 44e60fd54..c144504f4 100644 --- a/src/Commands/Syntex/PublishSyntexModel.cs +++ b/src/Commands/Syntex/PublishSyntexModel.cs @@ -109,7 +109,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("The connected site is not a Syntex Content Center site"); + LogWarning("The connected site is not a Syntex Content Center site"); } } } diff --git a/src/Commands/Syntex/UnPublishSyntexModel.cs b/src/Commands/Syntex/UnPublishSyntexModel.cs index c6d7ad736..bd8496ac6 100644 --- a/src/Commands/Syntex/UnPublishSyntexModel.cs +++ b/src/Commands/Syntex/UnPublishSyntexModel.cs @@ -105,7 +105,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("The connected site is not a Syntex Content Center site"); + LogWarning("The connected site is not a Syntex Content Center site"); } } } diff --git a/src/Commands/Taxonomy/ExportTaxonomy.cs b/src/Commands/Taxonomy/ExportTaxonomy.cs index b70c97c18..4fa1df567 100644 --- a/src/Commands/Taxonomy/ExportTaxonomy.cs +++ b/src/Commands/Taxonomy/ExportTaxonomy.cs @@ -92,7 +92,7 @@ protected override void ExecuteCmdlet() System.Text.Encoding textEncoding = System.Text.Encoding.Unicode; if (Encoding == Encoding.UTF7) { - WriteWarning("UTF-7 Encoding is no longer supported. Defaulting to UTF-8"); + LogWarning("UTF-7 Encoding is no longer supported. Defaulting to UTF-8"); Encoding = Encoding.UTF8; } switch (Encoding) diff --git a/src/Commands/Teams/GetTeamsTab.cs b/src/Commands/Teams/GetTeamsTab.cs index 6db6f338e..4fdf36a09 100644 --- a/src/Commands/Teams/GetTeamsTab.cs +++ b/src/Commands/Teams/GetTeamsTab.cs @@ -39,7 +39,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new PSArgumentException("Cannot find tab"), ErrorCategory.ObjectNotFound); + LogError(new PSArgumentException("Cannot find tab")); } } else @@ -49,12 +49,12 @@ protected override void ExecuteCmdlet() } else { - this.WriteError(new PSArgumentException("Channel not found"), ErrorCategory.ObjectNotFound); + this.LogError(new PSArgumentException("Channel not found")); } } else { - this.WriteError(new PSArgumentException("Team not found"), ErrorCategory.ObjectNotFound); + this.LogError(new PSArgumentException("Team not found")); } } } diff --git a/src/Commands/Teams/GetTeamsUser.cs b/src/Commands/Teams/GetTeamsUser.cs index 91daa6350..856520dc1 100644 --- a/src/Commands/Teams/GetTeamsUser.cs +++ b/src/Commands/Teams/GetTeamsUser.cs @@ -44,7 +44,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Specified channel is not a private channel. Please specify a private channel name to fetch its users."); + LogWarning("Specified channel is not a private channel. Please specify a private channel name to fetch its users."); } } else diff --git a/src/Commands/Teams/NewTeamsTeam.cs b/src/Commands/Teams/NewTeamsTeam.cs index e02502a70..90ffffde0 100644 --- a/src/Commands/Teams/NewTeamsTeam.cs +++ b/src/Commands/Teams/NewTeamsTeam.cs @@ -142,7 +142,7 @@ protected override void ExecuteCmdlet() if (SensitivityLabels != null && SensitivityLabels.Length > 0) { SensitivityLabels = null; - WriteWarning("Adding sensitivity labels in App-only context is not supported by Graph API, so it will be skipped in Team creation"); + LogWarning("Adding sensitivity labels in App-only context is not supported by Graph API, so it will be skipped in Team creation"); } } diff --git a/src/Commands/Teams/RemoveTeamsChannel.cs b/src/Commands/Teams/RemoveTeamsChannel.cs index 01dce3dd8..92f3dcf61 100644 --- a/src/Commands/Teams/RemoveTeamsChannel.cs +++ b/src/Commands/Teams/RemoveTeamsChannel.cs @@ -43,7 +43,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new Exception($"Channel remove failed"), "REMOVEFAILED", ErrorCategory.InvalidResult, this)); + LogError($"Channel remove failed"); } } } diff --git a/src/Commands/Teams/RemoveTeamsTeam.cs b/src/Commands/Teams/RemoveTeamsTeam.cs index 3624d09d1..b431794c4 100644 --- a/src/Commands/Teams/RemoveTeamsTeam.cs +++ b/src/Commands/Teams/RemoveTeamsTeam.cs @@ -37,7 +37,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new Exception($"Team remove failed"), "REMOVEFAILED", ErrorCategory.InvalidResult, this)); + LogError($"Team remove failed"); } } } diff --git a/src/Commands/ToDo/GetTodoList.cs b/src/Commands/ToDo/GetTodoList.cs index fed147250..261e25c2e 100644 --- a/src/Commands/ToDo/GetTodoList.cs +++ b/src/Commands/ToDo/GetTodoList.cs @@ -33,7 +33,7 @@ protected override void ExecuteCmdlet() var user = User.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) { - WriteWarning("Provided user not found"); + LogWarning("Provided user not found"); return; } url = $"/v1.0/users/{user.Id}/todo/lists"; diff --git a/src/Commands/ToDo/NewTodoList.cs b/src/Commands/ToDo/NewTodoList.cs index 6ba29b13c..d55c3cd60 100644 --- a/src/Commands/ToDo/NewTodoList.cs +++ b/src/Commands/ToDo/NewTodoList.cs @@ -33,7 +33,7 @@ protected override void ExecuteCmdlet() var user = User.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) { - WriteWarning("Provided user not found"); + LogWarning("Provided user not found"); return; } url = $"/v1.0/users/{user.Id}/todo/lists"; diff --git a/src/Commands/ToDo/RemoveTodoList.cs b/src/Commands/ToDo/RemoveTodoList.cs index fba96dc10..0e94d4da9 100644 --- a/src/Commands/ToDo/RemoveTodoList.cs +++ b/src/Commands/ToDo/RemoveTodoList.cs @@ -25,7 +25,7 @@ protected override void ExecuteCmdlet() var user = User.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) { - WriteWarning("Provided user not found"); + LogWarning("Provided user not found"); return; } url = $"/v1.0/users/{user.Id}/todo/lists/{Identity}"; @@ -35,7 +35,7 @@ protected override void ExecuteCmdlet() if (graphResult.StatusCode == System.Net.HttpStatusCode.NoContent) { - WriteVerbose("Todo list deleted successfully"); + LogDebug("Todo list deleted successfully"); } else { diff --git a/src/Commands/ToDo/UpdateTodoList.cs b/src/Commands/ToDo/UpdateTodoList.cs index 307d30621..5dd53c3bd 100644 --- a/src/Commands/ToDo/UpdateTodoList.cs +++ b/src/Commands/ToDo/UpdateTodoList.cs @@ -29,7 +29,7 @@ protected override void ExecuteCmdlet() var user = User.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) { - WriteWarning("Provided user not found"); + LogWarning("Provided user not found"); return; } url = $"/v1.0/users/{user.Id}/todo/lists/{Identity}"; diff --git a/src/Commands/UserProfiles/GetUserOneDriveQuota.cs b/src/Commands/UserProfiles/GetUserOneDriveQuota.cs index bd1d0e8c6..d65d4aa19 100644 --- a/src/Commands/UserProfiles/GetUserOneDriveQuota.cs +++ b/src/Commands/UserProfiles/GetUserOneDriveQuota.cs @@ -55,7 +55,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning($"Couldn't find onedrive quota for the account: {Account} "); + LogWarning($"Couldn't find onedrive quota for the account: {Account} "); } } } diff --git a/src/Commands/UserProfiles/GetUserProfilePhoto.cs b/src/Commands/UserProfiles/GetUserProfilePhoto.cs index f02a663fe..19312146d 100644 --- a/src/Commands/UserProfiles/GetUserProfilePhoto.cs +++ b/src/Commands/UserProfiles/GetUserProfilePhoto.cs @@ -30,7 +30,7 @@ public class GetUserProfilePhoto : PnPGraphCmdlet protected override void ExecuteCmdlet() { - WriteVerbose($"Looking up user provided through the {nameof(Identity)} parameter"); + LogDebug($"Looking up user provided through the {nameof(Identity)} parameter"); Model.AzureAD.User user = Identity.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) @@ -39,7 +39,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException($"User provided through the {nameof(Identity)} parameter could not be found"); } - WriteVerbose($"Setting profile photo for user {user.UserPrincipalName}"); + LogDebug($"Setting profile photo for user {user.UserPrincipalName}"); if (Filename == null) { diff --git a/src/Commands/UserProfiles/GetUserProfileProperty.cs b/src/Commands/UserProfiles/GetUserProfileProperty.cs index 0817f7bef..309b31b46 100644 --- a/src/Commands/UserProfiles/GetUserProfileProperty.cs +++ b/src/Commands/UserProfiles/GetUserProfileProperty.cs @@ -28,12 +28,12 @@ protected override void ExecuteCmdlet() // Loop through each of the requested users foreach (var account in Account) { - WriteVerbose($"Getting user profile properties for {account}"); + LogDebug($"Getting user profile properties for {account}"); var result = Tenant.EncodeClaim(account); AdminContext.ExecuteQueryRetry(); var currentAccount = result.Value; - WriteVerbose($"Account {account} encoded to {currentAccount}"); + LogDebug($"Account {account} encoded to {currentAccount}"); SortedDictionary upsDictionary = new(); @@ -41,7 +41,7 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Properties)) && Properties != null && Properties.Length > 0 && Properties.All(p => !basicProperties.Contains(p))) { // Specific user profile properties have been requested and none of them are basic user profile properties, return only those properties that have been requested - WriteVerbose($"Retrieving {Properties.Length} specific non basic user profile {(Properties.Length != 1 ? "properties" : "property")} for account {currentAccount}"); + LogDebug($"Retrieving {Properties.Length} specific non basic user profile {(Properties.Length != 1 ? "properties" : "property")} for account {currentAccount}"); UserProfilePropertiesForUser userProfilePropertiesForUser = new UserProfilePropertiesForUser(AdminContext, currentAccount, Properties); var userRequestedProperties = peopleManager.GetUserProfilePropertiesFor(userProfilePropertiesForUser); @@ -58,7 +58,7 @@ protected override void ExecuteCmdlet() else { // No specific user profile properties have been requested or there were basic user profile properties amongst them - WriteVerbose($"Retrieving all user profile properties for {currentAccount}"); + LogDebug($"Retrieving all user profile properties for {currentAccount}"); var userProfileProperties = peopleManager.GetPropertiesFor(currentAccount); AdminContext.Load(userProfileProperties); @@ -72,7 +72,7 @@ protected override void ExecuteCmdlet() // Check if we only need to output specific properties or all of them if (ParameterSpecified(nameof(Properties)) && Properties != null && Properties.Length > 0) { - WriteVerbose($"Adding specific {Properties.Length} user profile {(Properties.Length != 1 ? "properties" : "property")} to the output"); + LogDebug($"Adding specific {Properties.Length} user profile {(Properties.Length != 1 ? "properties" : "property")} to the output"); // Check if any of the base user profile properties have been requested and if so, add them to the output as well if (Properties.Contains("AccountName")) upsDictionary.Add("AccountName", userProfileProperties.AccountName); @@ -114,7 +114,7 @@ protected override void ExecuteCmdlet() else { // Add all of the basic user profile properties to the output - WriteVerbose("Adding all user profile properties to the output"); + LogDebug("Adding all user profile properties to the output"); upsDictionary.Add("AccountName", userProfileProperties.AccountName); upsDictionary.Add("DirectReports", userProfileProperties.DirectReports); diff --git a/src/Commands/UserProfiles/NewUPABulkImportJob.cs b/src/Commands/UserProfiles/NewUPABulkImportJob.cs index 63bcffdaa..93332b6da 100644 --- a/src/Commands/UserProfiles/NewUPABulkImportJob.cs +++ b/src/Commands/UserProfiles/NewUPABulkImportJob.cs @@ -62,7 +62,7 @@ protected override void ExecuteCmdlet() throw new InvalidEnumArgumentException(@"Path cannot be empty"); } - WriteVerbose($"Going to use mapping file to upload from {Path}"); + LogDebug($"Going to use mapping file to upload from {Path}"); var webCtx = AdminContext.Clone(Connection.Url); var web = webCtx.Web; @@ -82,12 +82,12 @@ protected override void ExecuteCmdlet() File file = null; if(!ParameterSpecified(nameof(WhatIf))) { - WriteVerbose($"Uploading file from {Path} to {fileName}"); + LogDebug($"Uploading file from {Path} to {fileName}"); file = folder.UploadFile(fileName, Path, true); } else { - WriteVerbose($"Skipping uploading file from {Path} to {fileName} due to {nameof(WhatIf)} parameter being specified"); + LogDebug($"Skipping uploading file from {Path} to {fileName} due to {nameof(WhatIf)} parameter being specified"); } Url = new Uri(webCtx.Url).GetLeftPart(UriPartial.Authority) + file?.ServerRelativeUrl; @@ -97,7 +97,7 @@ protected override void ExecuteCmdlet() { throw new InvalidEnumArgumentException(@"Url cannot be empty"); } - WriteVerbose($"Will instruct SharePoint Online to use mapping file located at {Url}"); + LogDebug($"Will instruct SharePoint Online to use mapping file located at {Url}"); break; } @@ -107,7 +107,7 @@ protected override void ExecuteCmdlet() Guid? jobId = null; if (!ParameterSpecified(nameof(WhatIf))) { - WriteVerbose($"Instructing SharePoint Online to queue user profile file located at {Url}"); + LogDebug($"Instructing SharePoint Online to queue user profile file located at {Url}"); var id = o365.QueueImportProfileProperties(IdType, IdProperty, propDictionary, Url); AdminContext.ExecuteQueryRetry(); @@ -118,14 +118,14 @@ protected override void ExecuteCmdlet() } else { - WriteVerbose($"Skipping instructing SharePoint Online to queue user profile file located at {Url} due to {nameof(WhatIf)} parameter being specified"); + LogDebug($"Skipping instructing SharePoint Online to queue user profile file located at {Url} due to {nameof(WhatIf)} parameter being specified"); return; } // For some reason it sometimes does not always properly return the JobId while the job did start. Show this in the output. if(!jobId.HasValue || jobId.Value == Guid.Empty) { - WriteWarning("The execution of the synchronization job did not return a job Id but seems to have started successfully. Use Get-PnPUPABulkImportStatus to check for the current status."); + LogWarning("The execution of the synchronization job did not return a job Id but seems to have started successfully. Use Get-PnPUPABulkImportStatus to check for the current status."); return; } @@ -133,7 +133,7 @@ protected override void ExecuteCmdlet() AdminContext.Load(job); AdminContext.ExecuteQueryRetry(); - WriteVerbose($"Job initiated with Id {job.JobId} and status {job.State} for file {job.SourceUri}"); + LogDebug($"Job initiated with Id {job.JobId} and status {job.State} for file {job.SourceUri}"); // Check if we should wait with finalzing this cmdlet execution until the user profile import operation has completed if(Wait.ToBool()) @@ -144,7 +144,7 @@ protected override void ExecuteCmdlet() do { // Wait before requesting its current state again to avoid running into throttling - WriteVerbose($"Waiting for {waitBetweenChecks} seconds before querying for the status of job Id {job.JobId}"); + LogDebug($"Waiting for {waitBetweenChecks} seconds before querying for the status of job Id {job.JobId}"); Thread.Sleep((int)System.TimeSpan.FromSeconds(waitBetweenChecks).TotalMilliseconds); // Request the current status of the import job @@ -152,7 +152,7 @@ protected override void ExecuteCmdlet() AdminContext.Load(jobStatus); AdminContext.ExecuteQueryRetry(); - WriteVerbose($"Current status of job {job.JobId}: {jobStatus.State}"); + LogDebug($"Current status of job {job.JobId}: {jobStatus.State}"); } while (jobStatus.State != ImportProfilePropertiesJobState.Succeeded && jobStatus.State != ImportProfilePropertiesJobState.Error); diff --git a/src/Commands/UserProfiles/RemoveUserProfile.cs b/src/Commands/UserProfiles/RemoveUserProfile.cs index 0e6a960bf..16bcbd960 100644 --- a/src/Commands/UserProfiles/RemoveUserProfile.cs +++ b/src/Commands/UserProfiles/RemoveUserProfile.cs @@ -33,7 +33,7 @@ protected override void ExecuteCmdlet() RestHelper.Post(Connection.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/HardDeleteUserProfile(accountName=@a,userId='{UserId}')?@a='{normalizedUserName}'", AdminContext); } - WriteVerbose($"Completed deletion of user profile {LoginName}"); + LogDebug($"Completed deletion of user profile {LoginName}"); } } } diff --git a/src/Commands/UserProfiles/RemoveUserProfilePhoto.cs b/src/Commands/UserProfiles/RemoveUserProfilePhoto.cs index f927307a6..ab2ed34d6 100644 --- a/src/Commands/UserProfiles/RemoveUserProfilePhoto.cs +++ b/src/Commands/UserProfiles/RemoveUserProfilePhoto.cs @@ -15,16 +15,16 @@ public class RemoveUserProfilePhoto : PnPGraphCmdlet public AzureADUserPipeBind Identity; protected override void ExecuteCmdlet() { - WriteVerbose($"Looking up user provided through the {nameof(Identity)} parameter"); + LogDebug($"Looking up user provided through the {nameof(Identity)} parameter"); Model.AzureAD.User user = Identity.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) { - WriteWarning($"User provided through the {nameof(Identity)} parameter could not be found"); + LogWarning($"User provided through the {nameof(Identity)} parameter could not be found"); return; } - WriteVerbose($"Removing profile photo for user {user.UserPrincipalName}"); + LogDebug($"Removing profile photo for user {user.UserPrincipalName}"); GraphRequestHelper.Delete($"users/{user.Id}/photo/$value"); } diff --git a/src/Commands/UserProfiles/SetUserProfilePhoto.cs b/src/Commands/UserProfiles/SetUserProfilePhoto.cs index 01825fdcb..59f8a3e72 100644 --- a/src/Commands/UserProfiles/SetUserProfilePhoto.cs +++ b/src/Commands/UserProfiles/SetUserProfilePhoto.cs @@ -21,16 +21,16 @@ public class SetUserProfilePhoto : PnPGraphCmdlet protected override void ExecuteCmdlet() { - WriteVerbose($"Looking up user provided through the {nameof(Identity)} parameter"); + LogDebug($"Looking up user provided through the {nameof(Identity)} parameter"); Model.AzureAD.User user = Identity.GetUser(AccessToken, Connection.AzureEnvironment); if (user == null) { - WriteWarning($"User provided through the {nameof(Identity)} parameter could not be found"); + LogWarning($"User provided through the {nameof(Identity)} parameter could not be found"); return; } - WriteVerbose($"Setting profile photo for user {user.UserPrincipalName}"); + LogDebug($"Setting profile photo for user {user.UserPrincipalName}"); if (!System.IO.Path.IsPathRooted(Path)) { diff --git a/src/Commands/UserProfiles/SyncSharePointUserProfilesFromAzureActiveDirectory.cs b/src/Commands/UserProfiles/SyncSharePointUserProfilesFromAzureActiveDirectory.cs index 6ff860d39..80489d528 100644 --- a/src/Commands/UserProfiles/SyncSharePointUserProfilesFromAzureActiveDirectory.cs +++ b/src/Commands/UserProfiles/SyncSharePointUserProfilesFromAzureActiveDirectory.cs @@ -47,13 +47,13 @@ protected override void ExecuteCmdlet() } if(Users.Count == 0) { - WriteVerbose("No users have been provided"); + LogDebug("No users have been provided"); return; } // Users to sync have been provided - WriteVerbose($"Using provided user collection containing {Users.Count} user{(Users.Count != 1 ? "s": "")}"); + LogDebug($"Using provided user collection containing {Users.Count} user{(Users.Count != 1 ? "s": "")}"); aadUsers = Users; } @@ -70,12 +70,12 @@ protected override void ExecuteCmdlet() } } - WriteVerbose("Retrieving users from Azure Active Directory"); + LogDebug("Retrieving users from Azure Active Directory"); // Retrieve all the users from Azure Active Directory aadUsers = PnP.PowerShell.Commands.Utilities.AzureAdUtility.ListUsers(GraphAccessToken, null, null, allAadPropertiesList.ToArray(), endIndex: null, azureEnvironment: Connection.AzureEnvironment); - WriteVerbose($"{aadUsers.Count} user{(aadUsers.Count != 1 ? "s have" : " has")} been retrieved from Azure Active Directory"); + LogDebug($"{aadUsers.Count} user{(aadUsers.Count != 1 ? "s have" : " has")} been retrieved from Azure Active Directory"); if (aadUsers.Count == 0) { @@ -87,7 +87,7 @@ protected override void ExecuteCmdlet() var nonAdminClientContext = ClientContext.Clone(Connection.Url); // Perform the mapping and execute the sync operation - WriteVerbose($"Creating mapping file{(WhatIf.ToBool() ? " and" : ",")} uploading it to SharePoint Online to folder '{Folder}'{(WhatIf.ToBool() ? "" : " and executing sync job")}"); + LogDebug($"Creating mapping file{(WhatIf.ToBool() ? " and" : ",")} uploading it to SharePoint Online to folder '{Folder}'{(WhatIf.ToBool() ? "" : " and executing sync job")}"); var job = Utilities.SharePointUserProfileSync.SyncFromAzureActiveDirectory(nonAdminClientContext, aadUsers, IdType, UserProfilePropertyMapping, Folder, ParameterSpecified(nameof(WhatIf))).GetAwaiter().GetResult(); // Ensure a sync job has been created @@ -96,7 +96,7 @@ protected override void ExecuteCmdlet() throw new PSInvalidOperationException($"Failed to create sync job. Ensure you're providing users to sync and that the mapping is correct."); } - WriteVerbose($"Job initiated with {(job.JobId.HasValue ? $"Id {job.JobId} and ": "")}status {job.State} for file {job.SourceUri}"); + LogDebug($"Job initiated with {(job.JobId.HasValue ? $"Id {job.JobId} and ": "")}status {job.State} for file {job.SourceUri}"); // Check if we should wait with finalzing this cmdlet execution until the user profile import operation has completed if (Wait.ToBool() && !WhatIf.ToBool()) @@ -115,7 +115,7 @@ protected override void ExecuteCmdlet() ClientContext.Load(jobStatus); ClientContext.ExecuteQueryRetry(); - WriteVerbose($"Current status of job {job.JobId.Value}: {jobStatus.State}"); + LogDebug($"Current status of job {job.JobId.Value}: {jobStatus.State}"); } while (jobStatus.State != ImportProfilePropertiesJobState.Succeeded && jobStatus.State != ImportProfilePropertiesJobState.Error); diff --git a/src/Commands/Utilities/AzureAuthHelper.cs b/src/Commands/Utilities/AzureAuthHelper.cs index 1fcf0bbe2..8bf38c5fe 100644 --- a/src/Commands/Utilities/AzureAuthHelper.cs +++ b/src/Commands/Utilities/AzureAuthHelper.cs @@ -36,7 +36,7 @@ internal static string AuthenticateDeviceLogin(CancellationTokenSource cancellat { ClipboardService.SetText(result.UserCode); - messageWriter.WriteWarning($"Please login.\n\nWe opened a browser and navigated to {result.VerificationUrl}\n\nEnter code: {result.UserCode} (we copied this code to your clipboard)\n\nNOTICE: close the browser tab after you authenticated successfully to continue the process."); + messageWriter.LogWarning($"Please login.\n\nWe opened a browser and navigated to {result.VerificationUrl}\n\nEnter code: {result.UserCode} (we copied this code to your clipboard)\n\nNOTICE: close the browser tab after you authenticated successfully to continue the process."); BrowserHelper.OpenBrowserForInteractiveLogin(result.VerificationUrl, BrowserHelper.FindFreeLocalhostRedirectUri(), cancellationTokenSource); return Task.FromResult(0); diff --git a/src/Commands/Utilities/CmdletMessageWriter.cs b/src/Commands/Utilities/CmdletMessageWriter.cs index 300810319..909b7c975 100644 --- a/src/Commands/Utilities/CmdletMessageWriter.cs +++ b/src/Commands/Utilities/CmdletMessageWriter.cs @@ -3,16 +3,17 @@ using System.Linq; using System.Management.Automation; using System.Threading; +using PnP.PowerShell.Commands.Base; namespace PnP.PowerShell.Commands.Utilities { public class CmdletMessageWriter { - private PSCmdlet Cmdlet { get; set; } + private BasePSCmdlet Cmdlet { get; set; } private Queue Queue { get; set; } private object LockToken { get; set; } public bool Finished { get; set; } - public CmdletMessageWriter(PSCmdlet cmdlet) + public CmdletMessageWriter(BasePSCmdlet cmdlet) { this.Cmdlet = cmdlet; this.LockToken = new object(); @@ -65,7 +66,7 @@ public void Start() Thread.Sleep(100); } - public void WriteWarning(string message, bool formatted = true) + public void LogWarning(string message, bool formatted = true) { lock (LockToken) { @@ -82,7 +83,7 @@ public void WriteMessage(string message, bool formatted = true) } } - public void WriteVerbose(string message) + public void LogDebug(string message) { if (Cmdlet.MyInvocation.BoundParameters.ContainsKey("Verbose")) { @@ -126,12 +127,12 @@ private static List WordWrap(string text, int maxLineLength) return list; } - internal static void WriteFormattedWarning(PSCmdlet cmdlet, string message) + internal static void WriteFormattedWarning(BasePSCmdlet cmdlet, string message) { WriteFormattedMessage(cmdlet, new Message { Text = message, Type = MessageType.Warning, Formatted = true }); } - internal static void WriteFormattedMessage(PSCmdlet cmdlet, Message message) + internal static void WriteFormattedMessage(BasePSCmdlet cmdlet, Message message) { if (cmdlet.Host.Name == "ConsoleHost" && cmdlet.Host.UI.RawUI.MaxWindowSize.Width > 8) { @@ -170,12 +171,12 @@ internal static void WriteFormattedMessage(PSCmdlet cmdlet, Message message) } case MessageType.Warning: { - cmdlet.WriteWarning($"{notificationColor}\n{outMessage}{resetColor}\n"); + cmdlet.LogWarning($"{notificationColor}\n{outMessage}{resetColor}\n"); break; } case MessageType.Verbose: { - cmdlet.WriteVerbose(outMessage); + cmdlet.LogDebug(outMessage); break; } } @@ -191,12 +192,12 @@ internal static void WriteFormattedMessage(PSCmdlet cmdlet, Message message) } case MessageType.Warning: { - cmdlet.WriteWarning(message.Text); + cmdlet.LogWarning(message.Text); break; } case MessageType.Verbose: { - cmdlet.WriteVerbose(message.Text); + cmdlet.LogDebug(message.Text); break; } } diff --git a/src/Commands/Utilities/ListItemHelper.cs b/src/Commands/Utilities/ListItemHelper.cs index 792044cf7..96e0a18c2 100644 --- a/src/Commands/Utilities/ListItemHelper.cs +++ b/src/Commands/Utilities/ListItemHelper.cs @@ -1,6 +1,7 @@ using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Taxonomy; using PnP.Core.QueryModel; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Enums; using PnP.PowerShell.Commands.Model; using System; @@ -33,7 +34,7 @@ public FieldUpdateValue(string key, object value, string fieldTypeString) } } - public static void SetFieldValues(this ListItem item, Hashtable valuesToSet, Cmdlet cmdlet) + public static void SetFieldValues(this ListItem item, Hashtable valuesToSet, BasePSCmdlet cmdlet) { var itemValues = new List(); @@ -68,7 +69,7 @@ public static void SetFieldValues(this ListItem item, Hashtable valuesToSet, Cmd if (value is string && string.IsNullOrWhiteSpace(value + "")) goto default; if (value.GetType().IsArray) { - foreach (var arrayItem in (value as IEnumerable)) + foreach (var arrayItem in value as IEnumerable) { int userId; if (!int.TryParse(arrayItem.ToString(), out userId)) @@ -131,7 +132,7 @@ public static void SetFieldValues(this ListItem item, Hashtable valuesToSet, Cmd } else { - cmdlet.WriteWarning("Unable to find the specified term. Skipping values for field '" + field.InternalName + "'."); + cmdlet.LogWarning("Unable to find the specified term. Skipping values for field '" + field.InternalName + "'."); } } @@ -155,7 +156,7 @@ public static void SetFieldValues(this ListItem item, Hashtable valuesToSet, Cmd } else { - cmdlet.WriteWarning("You are trying to set multiple values in a single value field. Skipping values for field '" + field.InternalName + "'."); + cmdlet.LogWarning("You are trying to set multiple values in a single value field. Skipping values for field '" + field.InternalName + "'."); } } else @@ -172,7 +173,7 @@ public static void SetFieldValues(this ListItem item, Hashtable valuesToSet, Cmd if (taxonomyItem == null) { updateTaxItemValue = false; - cmdlet.WriteWarning("Unable to find the specified term. Skipping values for field '" + field.InternalName + "'."); + cmdlet.LogWarning("Unable to find the specified term. Skipping values for field '" + field.InternalName + "'."); } } else diff --git a/src/Commands/Utilities/Logging/LogStreamListener.cs b/src/Commands/Utilities/Logging/LogStreamListener.cs new file mode 100644 index 000000000..4805e0540 --- /dev/null +++ b/src/Commands/Utilities/Logging/LogStreamListener.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace PnP.PowerShell.Commands.Utilities.Logging +{ + /// + /// Tracel listener that captures log entries in a list in memory so they can be retrieved in PowerShell without having to write them to a file + /// + public class LogStreamListener : TraceListener + { + /// + /// The default name of the log stream listener. This is used to identify the listener in the Trace.Listeners collection. + /// + public const string DefaultListenerName = "PNPPOWERSHELLLOGSTREAMTRACELISTENER"; + + /// + /// The list of log entries captured by this listener. This is used to retrieve the log entries in PowerShell. + /// + public List Entries { get; } = []; + + /// + /// Receives a message that is being logged + /// + /// Message that is being logged + public override void Write(string message) + { + // Ignore the message, we only care about WriteLine as these partial messages are not complete log entries + } + + /// + /// Receives a message that is being logged + /// + /// Message that is being logged + public override void WriteLine(string message) + { + // Check if we received a message + if (string.IsNullOrWhiteSpace(message)) return; + + // Split the message into parts. The message is tab separated. + var items = message.Split('\t'); + + // Ensure we have at least 7 items in the message + if (items.Length < 7) return; + + // Try to parse the message into a TraceLogEntry. If it fails, ignore the message. + Entries.Add(new TraceLogEntry(items)); + } + } +} \ No newline at end of file diff --git a/src/Commands/Utilities/Logging/LoggingUtility.cs b/src/Commands/Utilities/Logging/LoggingUtility.cs new file mode 100644 index 000000000..b2e442c71 --- /dev/null +++ b/src/Commands/Utilities/Logging/LoggingUtility.cs @@ -0,0 +1,158 @@ +using System; +using System.Diagnostics; +using System.Management.Automation; +using System.Reflection; +using PnP.Framework.Diagnostics; + +namespace PnP.PowerShell.Commands.Utilities.Logging +{ + /// + /// Utility class that allows loging messages + /// + internal static class LoggingUtility + { + /// + /// Keep a reference to the last log time and correlation id to calculate the elapsed time between log entries + /// + private static DateTime? _lastLogTime = null; + + /// + /// Keep a reference to the last correlation id to calculate the elapsed time between log entries, but reset counting when the correlation id changes + /// + private static Guid? _lastCorrelationId = null; + + /// + /// Logs a debug message to the log stream and writes it to the cmdlet output as well + /// + /// Cmdlet currently being executed + /// The message to log + /// The source from where is being logged. Leave NULL to have it use the cmdlet name automatically. + /// The correlation of the cmdlet execution + /// The elapsed milliseconds since the last log entry. Leave NULL to try to calculate it automatically. + public static void Debug(Cmdlet cmdlet, string message, string source = null, Guid? correlationId = null, long? ellapsedMilliseconds = null) + { + Log.Debug(ComposeLogEntry(cmdlet, message, source, correlationId, ellapsedMilliseconds)); + cmdlet?.WriteVerbose(message); + } + + /// + /// Logs a warning message to the log stream and writes it to the cmdlet output as well + /// + /// Cmdlet currently being executed + /// The message to log + /// The source from where is being logged. Leave NULL to have it use the cmdlet name automatically. + /// The correlation of the cmdlet execution + /// The elapsed milliseconds since the last log entry. Leave NULL to try to calculate it automatically. + public static void Warning(Cmdlet cmdlet, string message, string source = null, Guid? correlationId = null, long? ellapsedMilliseconds = null) + { + Log.Warning(ComposeLogEntry(cmdlet, message, source, correlationId, ellapsedMilliseconds)); + cmdlet?.WriteWarning(message); + } + + /// + /// Logs an informational message to the log stream and writes it to the cmdlet output as well + /// + /// Cmdlet currently being executed + /// The message to log + /// The source from where is being logged. Leave NULL to have it use the cmdlet name automatically. + /// The correlation of the cmdlet execution + /// The elapsed milliseconds since the last log entry. Leave NULL to try to calculate it automatically. + public static void Info(Cmdlet cmdlet, string message, string source = null, Guid? correlationId = null, long? ellapsedMilliseconds = null) + { + Log.Info(ComposeLogEntry(cmdlet, message, source, correlationId, ellapsedMilliseconds)); + cmdlet?.WriteInformation(new InformationRecord(message, DefineCmdletName(cmdlet))); + } + + /// + /// Logs an error message to the log stream and writes it to the cmdlet output as well + /// + /// Cmdlet currently being executed + /// The message to log + /// The source from where is being logged. Leave NULL to have it use the cmdlet name automatically. + /// The correlation of the cmdlet execution + /// The elapsed milliseconds since the last log entry. Leave NULL to try to calculate it automatically. + public static void Error(Cmdlet cmdlet, string message, string source = null, Guid? correlationId = null, long? ellapsedMilliseconds = null) + { + Log.Error(ComposeLogEntry(cmdlet, message, source, correlationId, ellapsedMilliseconds)); + cmdlet?.WriteError(new ErrorRecord(new Exception(message), source, ErrorCategory.NotSpecified, null)); + } + + /// + /// Defines the cmdlet name based on the CmdletAttribute or the type name of the cmdlet. + /// + /// Cmdlet to define its name for + /// Name of the cmdlet + private static string DefineCmdletName(Cmdlet cmdlet) + { + if (cmdlet == null) + { + return string.Empty; + } + + if (cmdlet.GetType().GetCustomAttribute(typeof(CmdletAttribute)) is CmdletAttribute cmdletAttribute) + { + return $"{cmdletAttribute.VerbName}-{cmdletAttribute.NounName}"; + } + else + { + return cmdlet.GetType().Name; + } + } + + /// + /// Composes a log entry based on the cmdlet, message, source and correlation id + /// + /// Cmdlet currently being executed + /// The message to log + /// The source from where is being logged. Leave NULL to have it use the cmdlet name automatically. + /// The correlation of the cmdlet execution + /// The elapsed milliseconds since the last log entry. Leave NULL to try to calculate it automatically. + /// + private static LogEntry ComposeLogEntry(Cmdlet cmdlet, string message, string source = null, Guid? correlationId = null, long? ellapsedMilliseconds = null) + { + if (_lastCorrelationId != correlationId && correlationId.HasValue) + { + // New cmdlet execution, reset the last log time + _lastLogTime = null; + _lastCorrelationId = correlationId; + } + + var logEntry = new LogEntry + { + Message = message, + CorrelationId = correlationId ?? Guid.Empty, + EllapsedMilliseconds = ellapsedMilliseconds ?? (_lastLogTime.HasValue ? (long)DateTime.UtcNow.Subtract(_lastLogTime.Value).TotalMilliseconds : 0), + Source = source ?? DefineCmdletName(cmdlet), + ThreadId = Environment.CurrentManagedThreadId + }; + + // Keep a reference to the last log time to calculate the elapsed time between log entries + _lastLogTime = DateTime.UtcNow; + + return logEntry; + } + + /// + /// Tries to remove the listener with the given name from the Trace.Listeners collection. + /// If the listener is not found, it will be ignored. + /// + /// Name of the trace listener + public static void RemoveListener(string listenerName) + { + try + { + var existingListener = Trace.Listeners[listenerName]; + if (existingListener != null) + { + existingListener.Flush(); + existingListener.Close(); + Trace.Listeners.Remove(existingListener); + } + } + catch (Exception) + { + // ignored + } + } + } +} \ No newline at end of file diff --git a/src/Commands/Utilities/Logging/TraceLogEntry.cs b/src/Commands/Utilities/Logging/TraceLogEntry.cs new file mode 100644 index 000000000..74a3f1126 --- /dev/null +++ b/src/Commands/Utilities/Logging/TraceLogEntry.cs @@ -0,0 +1,45 @@ +using System; + +namespace PnP.PowerShell.Commands.Utilities.Logging +{ + /// + /// Represents a single entry in the trace log + /// + public class TraceLogEntry(string[] values) + { + /// + /// The time stamp of the log entry + /// + public DateTime? TimeStamp = DateTime.TryParse(values[0], out var timeStamp) ? timeStamp : null; + + /// + /// The category of the log entry + /// + public string Source = values[1].Trim('[', ']'); + + /// + /// Id of the thread on which the log entry was created + /// + public int? ThreadId { get; set; } = int.TryParse(values[2].Trim('[', ']'), out var threadId) ? threadId : null; + + /// + /// The level of the log entry + /// + public Framework.Diagnostics.LogLevel? Level = Enum.TryParse(values[3].Trim('[', ']'), out var logLevel) ? logLevel : null; + + /// + /// The logged message + /// + public string Message = values[4]; + + /// + /// The elapsed Log time in MilliSeconds sicne the previous entry + /// + public long? EllapsedMilliseconds { get; set; } = long.TryParse(values[5][..^2], out var ellapsedMilliseconds) ? ellapsedMilliseconds : null; + + /// + /// The CorrelationId representing the log entry + /// + public Guid? CorrelationId { get; set; } = Guid.TryParse(values[6], out var correlationId) ? correlationId : null; + } +} \ No newline at end of file diff --git a/src/Commands/Utilities/REST/ApiRequestHelper.cs b/src/Commands/Utilities/REST/ApiRequestHelper.cs index 086530fdf..03132f5e5 100644 --- a/src/Commands/Utilities/REST/ApiRequestHelper.cs +++ b/src/Commands/Utilities/REST/ApiRequestHelper.cs @@ -265,7 +265,7 @@ public T Get(string url, bool camlCasePolicy = true, bool propertyNameCaseIns catch (Exception e) { LogError($"Failed to parse response from server. Error message: '{e.Message}'. Received content: '{stringContent}'. Model type to parse it to: '{typeof(T)}'."); - //Cmdlet.WriteWarning($"Failed to parse response from server. Error message: '{e.Message}'. Received content: '{stringContent}'. Model type to parse it to: '{typeof(T)}'."); + //Cmdlet.LogWarning($"Failed to parse response from server. Error message: '{e.Message}'. Received content: '{stringContent}'. Model type to parse it to: '{typeof(T)}'."); return default; } } diff --git a/src/Commands/Utilities/SendMail.cs b/src/Commands/Utilities/SendMail.cs index dbe7b1895..5917fbea0 100644 --- a/src/Commands/Utilities/SendMail.cs +++ b/src/Commands/Utilities/SendMail.cs @@ -69,13 +69,13 @@ protected override void ExecuteCmdlet() { if (string.IsNullOrWhiteSpace(From)) { - WriteVerbose("Sending e-mail through SharePoint Online"); - WriteWarning("\n The SharePoint SendEmail API will be retired on October 31, 2025, and this method of sending emails will stop working. \n Please update your script to use Microsoft Graph as described here: https://pnp.github.io/powershell/cmdlets/Send-PnPMail.html#send-through-microsoft-graph \n Learn more: https://devblogs.microsoft.com/microsoft365dev/retirement-of-the-sharepoint-sendemail-api"); + LogDebug("Sending e-mail through SharePoint Online"); + LogWarning("\n The SharePoint SendEmail API will be retired on October 31, 2025, and this method of sending emails will stop working. \n Please update your script to use Microsoft Graph as described here: https://pnp.github.io/powershell/cmdlets/Send-PnPMail.html#send-through-microsoft-graph \n Learn more: https://devblogs.microsoft.com/microsoft365dev/retirement-of-the-sharepoint-sendemail-api"); MailUtility.SendSharePointEmail(ClientContext, Subject, Body, To, Cc, Bcc); } else { - WriteVerbose($"Sending e-mail using Microsoft Graph"); + LogDebug($"Sending e-mail using Microsoft Graph"); List messageAttachmentOptions = null; if (ParameterSpecified(nameof(Attachments))) { @@ -104,7 +104,7 @@ protected override void ExecuteCmdlet() }, SaveToSentItems ?? true); } - WriteVerbose($"E-mail sent successfully"); + LogDebug($"E-mail sent successfully"); } } } diff --git a/src/Commands/Utilities/VersionChecker.cs b/src/Commands/Utilities/VersionChecker.cs index 5db7fa5ee..a21c22d8c 100644 --- a/src/Commands/Utilities/VersionChecker.cs +++ b/src/Commands/Utilities/VersionChecker.cs @@ -5,6 +5,7 @@ using System.Net.Http; using System.Reflection; using System.Xml.Linq; +using PnP.PowerShell.Commands.Base; namespace PnP.PowerShell.Commands.Utilities { @@ -40,7 +41,7 @@ public static class VersionChecker /// Performs the check for a newer PnP PowerShell version /// /// Cmdlet instance from which this check is done - public static void CheckVersion(PSCmdlet cmdlet) + public static void CheckVersion(BasePSCmdlet cmdlet) { // Do we need to check versions: is the environment variable set? var pnppowershellUpdatecheck = Environment.GetEnvironmentVariable("PNPPOWERSHELL_UPDATECHECK"); @@ -64,7 +65,7 @@ public static void CheckVersion(PSCmdlet cmdlet) var productVersion = versionInfo.ProductVersion; var isNightly = productVersion.Contains("-"); - cmdlet?.WriteVerbose($"Checking for updates, current version is {productVersion}. See https://pnp.github.io/powershell/articles/configuration.html#disable-or-enable-version-checks for more information."); + cmdlet?.LogDebug($"Checking for updates, current version is {productVersion}. See https://pnp.github.io/powershell/articles/configuration.html#disable-or-enable-version-checks for more information."); // Check for the latest available version var onlineVersion = GetAvailableVersion3(isNightly); @@ -81,7 +82,7 @@ public static void CheckVersion(PSCmdlet cmdlet) } else { - cmdlet?.WriteVerbose($"No newer version of PnP PowerShell is available, latest available version is {onlineVersion.Version}"); + cmdlet?.LogDebug($"No newer version of PnP PowerShell is available, latest available version is {onlineVersion.Version}"); } if (!string.IsNullOrEmpty(onlineVersion.Message)) { @@ -95,7 +96,7 @@ public static void CheckVersion(PSCmdlet cmdlet) } catch (Exception e) { - cmdlet?.WriteVerbose($"Error checking for updates: {e.Message}"); + cmdlet?.LogDebug($"Error checking for updates: {e.Message}"); } } diff --git a/src/Commands/Viva/AddVivaConnectionsDashboardACE.cs b/src/Commands/Viva/AddVivaConnectionsDashboardACE.cs index e6518ff95..ca3b1eec9 100644 --- a/src/Commands/Viva/AddVivaConnectionsDashboardACE.cs +++ b/src/Commands/Viva/AddVivaConnectionsDashboardACE.cs @@ -70,7 +70,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Connected site is not a home site"); + LogWarning("Connected site is not a home site"); } } } diff --git a/src/Commands/Viva/GetVivaConnectionsDashboardACE.cs b/src/Commands/Viva/GetVivaConnectionsDashboardACE.cs index 6ba56b87f..c2d2033b9 100644 --- a/src/Commands/Viva/GetVivaConnectionsDashboardACE.cs +++ b/src/Commands/Viva/GetVivaConnectionsDashboardACE.cs @@ -26,7 +26,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("ACE with specified identifier not found"); + LogWarning("ACE with specified identifier not found"); } } else @@ -36,7 +36,7 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("Connected site is not a home site"); + LogWarning("Connected site is not a home site"); } } } diff --git a/src/Commands/Viva/RemoveVivaConnectionsDashboardACE.cs b/src/Commands/Viva/RemoveVivaConnectionsDashboardACE.cs index 2ae17bef1..28e175c26 100644 --- a/src/Commands/Viva/RemoveVivaConnectionsDashboardACE.cs +++ b/src/Commands/Viva/RemoveVivaConnectionsDashboardACE.cs @@ -25,12 +25,12 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("ACE with specified identifier not found"); + LogWarning("ACE with specified identifier not found"); } } else { - WriteWarning("Connected site is not a home site"); + LogWarning("Connected site is not a home site"); } } } diff --git a/src/Commands/Viva/SetVivaConnectionsDashboardACE.cs b/src/Commands/Viva/SetVivaConnectionsDashboardACE.cs index f8ab3093e..8b836644d 100644 --- a/src/Commands/Viva/SetVivaConnectionsDashboardACE.cs +++ b/src/Commands/Viva/SetVivaConnectionsDashboardACE.cs @@ -112,12 +112,12 @@ protected override void ExecuteCmdlet() } else { - WriteWarning("ACE with specified identifier not found"); + LogWarning("ACE with specified identifier not found"); } } else { - WriteWarning("Connected site is not a home site"); + LogWarning("Connected site is not a home site"); } } } diff --git a/src/Commands/Web/RemovePropertyBagValue.cs b/src/Commands/Web/RemovePropertyBagValue.cs index 7b492b947..561aa175f 100644 --- a/src/Commands/Web/RemovePropertyBagValue.cs +++ b/src/Commands/Web/RemovePropertyBagValue.cs @@ -25,14 +25,14 @@ protected override void ExecuteCmdlet() bool isScriptSettingUpdated = false; try { - WriteVerbose("Checking if the site is a no-script site"); + LogDebug("Checking if the site is a no-script site"); var web = ClientContext.Web; web.EnsureProperties(w => w.Url, w => w.ServerRelativeUrl); if (web.IsNoScriptSite()) { if (Force || ShouldContinue("The current site is a no-script site. Do you want to temporarily enable scripting on it to allow setting property bag value?", Properties.Resources.Confirm)) { - WriteVerbose("Temporarily enabling scripting on the site"); + LogDebug("Temporarily enabling scripting on the site"); var tenant = new Tenant(AdminContext); tenant.SetSiteProperties(web.Url, noScriptSite: false); isScriptSettingUpdated = true; @@ -84,7 +84,7 @@ protected override void ExecuteCmdlet() { if (isScriptSettingUpdated) { - WriteVerbose("Disabling scripting on the site"); + LogDebug("Disabling scripting on the site"); var tenant = new Tenant(AdminContext); tenant.SetSiteProperties(ClientContext.Web.Url, noScriptSite: true); } diff --git a/src/Commands/Web/SetPropertyBagValue.cs b/src/Commands/Web/SetPropertyBagValue.cs index f6171841d..62980b022 100644 --- a/src/Commands/Web/SetPropertyBagValue.cs +++ b/src/Commands/Web/SetPropertyBagValue.cs @@ -36,7 +36,7 @@ protected override void ExecuteCmdlet() bool isScriptSettingUpdated = false; try { - WriteVerbose("Checking if AllowWebPropertyBagUpdateWhenDenyAddAndCustomizePagesIsEnabled is set to true at the tenant level"); + LogDebug("Checking if AllowWebPropertyBagUpdateWhenDenyAddAndCustomizePagesIsEnabled is set to true at the tenant level"); var tenant = new Tenant(AdminContext); AdminContext.Load(tenant); AdminContext.Load(tenant, t => t.AllowWebPropertyBagUpdateWhenDenyAddAndCustomizePagesIsEnabled); @@ -45,7 +45,7 @@ protected override void ExecuteCmdlet() var web = ClientContext.Web; if (!tenant.AllowWebPropertyBagUpdateWhenDenyAddAndCustomizePagesIsEnabled) { - WriteVerbose("Checking if the site is a no-script site"); + LogDebug("Checking if the site is a no-script site"); web.EnsureProperties(w => w.Url, w => w.ServerRelativeUrl); @@ -53,7 +53,7 @@ protected override void ExecuteCmdlet() { if (Force || ShouldContinue("The current site is a no-script site. Do you want to temporarily enable scripting on it to allow setting property bag value?", Properties.Resources.Confirm)) { - WriteVerbose("Temporarily enabling scripting on the site"); + LogDebug("Temporarily enabling scripting on the site"); tenant.SetSiteProperties(web.Url, noScriptSite: false); isScriptSettingUpdated = true; } @@ -102,7 +102,7 @@ protected override void ExecuteCmdlet() { if (isScriptSettingUpdated) { - WriteVerbose("Disabling scripting on the site"); + LogDebug("Disabling scripting on the site"); var tenant = new Tenant(AdminContext); tenant.SetSiteProperties(ClientContext.Web.Url, noScriptSite: true); } diff --git a/src/Commands/Web/SetWebHeader.cs b/src/Commands/Web/SetWebHeader.cs index 742fbbb3b..33235e346 100644 --- a/src/Commands/Web/SetWebHeader.cs +++ b/src/Commands/Web/SetWebHeader.cs @@ -53,28 +53,28 @@ protected override void ExecuteCmdlet() if(ParameterSpecified(nameof(LogoAlignment))) { - WriteVerbose($"Setting site logo alignment to '{LogoAlignment}'"); + LogDebug($"Setting site logo alignment to '{LogoAlignment}'"); CurrentWeb.LogoAlignment = LogoAlignment; requiresWebUpdate = true; } if(ParameterSpecified(nameof(HeaderLayout))) { - WriteVerbose($"Setting header layout to '{HeaderLayout}'"); + LogDebug($"Setting header layout to '{HeaderLayout}'"); CurrentWeb.HeaderLayout = HeaderLayout; requiresWebUpdate = true; } if(ParameterSpecified(nameof(HeaderEmphasis))) { - WriteVerbose($"Setting header emphasis to '{HeaderEmphasis}'"); + LogDebug($"Setting header emphasis to '{HeaderEmphasis}'"); CurrentWeb.HeaderEmphasis = HeaderEmphasis; requiresWebUpdate = true; } if(ParameterSpecified(nameof(HideTitleInHeader))) { - WriteVerbose($"Setting hide title in header to '{HideTitleInHeader}'"); + LogDebug($"Setting hide title in header to '{HideTitleInHeader}'"); CurrentWeb.HideTitleInHeader = HideTitleInHeader; requiresWebUpdate = true; } @@ -85,22 +85,22 @@ protected override void ExecuteCmdlet() if(ParameterSpecified(nameof(HeaderBackgroundImageUrl))) { - WriteVerbose($"Setting header background image to '{HeaderBackgroundImageUrl}'"); + LogDebug($"Setting header background image to '{HeaderBackgroundImageUrl}'"); setSiteBackgroundImageInstructions.Add("\"relativeLogoUrl\":\"" + UrlUtilities.UrlEncode(HeaderBackgroundImageUrl) + "\""); } else { - WriteVerbose($"Setting header background image isFocalPatch to 'true'"); + LogDebug($"Setting header background image isFocalPatch to 'true'"); setSiteBackgroundImageInstructions.Add("\"isFocalPatch\":true"); } if(ParameterSpecified(nameof(HeaderBackgroundImageFocalX))) { - WriteVerbose($"Setting header background image focal point X to '{HeaderBackgroundImageFocalX.ToString().Replace(',', '.')}'"); + LogDebug($"Setting header background image focal point X to '{HeaderBackgroundImageFocalX.ToString().Replace(',', '.')}'"); setSiteBackgroundImageInstructions.Add("\"focalx\":" + HeaderBackgroundImageFocalX.ToString().Replace(',', '.')); } if(ParameterSpecified(nameof(HeaderBackgroundImageFocalY))) { - WriteVerbose($"Setting header background image focal point Y to '{HeaderBackgroundImageFocalY.ToString().Replace(',', '.')}'"); + LogDebug($"Setting header background image focal point Y to '{HeaderBackgroundImageFocalY.ToString().Replace(',', '.')}'"); setSiteBackgroundImageInstructions.Add("\"focaly\":" + HeaderBackgroundImageFocalY.ToString().Replace(',', '.')); } @@ -110,26 +110,26 @@ protected override void ExecuteCmdlet() stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); CurrentWeb.EnsureProperties(p => p.Url); var result = RequestHelper.PostHttpContent($"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", stringContent); - WriteVerbose($"Response from setsitelogo request: {result.StatusCode}"); + LogDebug($"Response from setsitelogo request: {result.StatusCode}"); } } if (requiresWebUpdate) { - WriteVerbose("Updating web"); + LogDebug("Updating web"); CurrentWeb.Update(); ClientContext.ExecuteQueryRetry(); } } private void SetSiteImage(string imageUrl, string imageType, int aspect) { - WriteVerbose($"Setting site {imageType} image to '{imageUrl}'"); + LogDebug($"Setting site {imageType} image to '{imageUrl}'"); var stringContent = new StringContent($"{{\"relativeLogoUrl\":\"{imageUrl}\",\"type\":0,\"aspect\":{aspect}}}"); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); CurrentWeb.EnsureProperties(p => p.Url); var result = RequestHelper.PostHttpContent($"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", stringContent); - WriteVerbose($"Response from {imageType} request: {result.StatusCode}"); + LogDebug($"Response from {imageType} request: {result.StatusCode}"); } } } diff --git a/src/Commands/Web/SetWebPermission.cs b/src/Commands/Web/SetWebPermission.cs index 3410dfba2..f877e3e87 100644 --- a/src/Commands/Web/SetWebPermission.cs +++ b/src/Commands/Web/SetWebPermission.cs @@ -81,7 +81,7 @@ protected override void ExecuteCmdlet() } else { - WriteError(new ErrorRecord(new Exception("Principal not found"), "1", ErrorCategory.ObjectNotFound, null)); + LogError("Principal not found"); } } }