From b16468e561ea7093d849b8fedc72aac00835d686 Mon Sep 17 00:00:00 2001 From: Koen Zomers Date: Tue, 31 May 2022 02:42:30 +0200 Subject: [PATCH 1/6] Bugfixes and code cleanup --- CHANGELOG.md | 2 + documentation/Get-PnPConnection.md | 22 +++++++-- documentation/Get-PnPContext.md | 22 +++++++-- documentation/Get-PnPList.md | 30 ++++++------ src/Commands/Base/BasePSCmdlet.cs | 5 -- src/Commands/Base/ConnectOnline.cs | 13 ++++-- src/Commands/Base/DisconnectOnline.cs | 51 +++++---------------- src/Commands/Base/GetConnection.cs | 24 ++-------- src/Commands/Base/GetContext.cs | 24 ++-------- src/Commands/Base/PnPConnectedCmdlet.cs | 13 ++++-- src/Commands/Base/PnPConnection.cs | 2 + src/Commands/Base/PnPSharePointCmdlet.cs | 41 ++++++++++------- src/Commands/Base/PnPWebRetrievalsCmdlet.cs | 18 ++++---- 13 files changed, 118 insertions(+), 149 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bab2d0cb7..bfa3757b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Fixed `Invoke-PnPSPRestMethod` invalid parsing for SharePoint number columns. [#1877](https://github.com/pnp/powershell/pull/1879) - Fix issue with `Add/Set-PnPListItem` not throwing correct exception for invalid taxonomy values. [#1870](https://github.com/pnp/powershell/pull/1870) - Fixed `Sync-PnPSharePointUserProfilesFromAzureActiveDirectory` throwing an "Object reference not set to an instance of an object" exception when providing an empty users collection or incorrect user mapping [#1896](https://github.com/pnp/powershell/pull/1896) +- Fixed `Connect-PnPOnline -ReturnConnection` also setting the current connection instead of just the returned connection +- Fixed `Disconnect-PnPOnline -Connection` also disconnecting other connections next to the provided connection ### Removed - Removed `Get-PnPAvailableClientSideComponents`. Use `Get-PnPPageComponent -Page -ListAvailable` instead. [#1833](https://github.com/pnp/powershell/pull/1833) diff --git a/documentation/Get-PnPConnection.md b/documentation/Get-PnPConnection.md index f0a033f12..c67553c36 100644 --- a/documentation/Get-PnPConnection.md +++ b/documentation/Get-PnPConnection.md @@ -10,12 +10,12 @@ title: Get-PnPConnection # Get-PnPConnection ## SYNOPSIS -Returns the current context +Returns the current connection ## SYNTAX ```powershell -Get-PnPConnection [] +Get-PnPConnection [-Connection ] [] ``` ## DESCRIPTION @@ -32,8 +32,22 @@ This will put the current connection for use with the -Connection parameter on o ## PARAMETERS -## RELATED LINKS +### -Connection +Optional connection to be used by the cmdlet. Retrieve the value for this parameter by specifying -ReturnConnection on Connect-PnPOnline. If not provided, the connection will be retrieved from the current context. + +```yaml -[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) +```yaml +Type: PnPConnection +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-PnPContext.md b/documentation/Get-PnPContext.md index 81e213c75..100f615e3 100644 --- a/documentation/Get-PnPContext.md +++ b/documentation/Get-PnPContext.md @@ -10,16 +10,16 @@ title: Get-PnPContext # Get-PnPContext ## SYNOPSIS -Returns the current context +Returns the current SharePoint Online CSOM context ## SYNTAX ```powershell -Get-PnPContext [] +Get-PnPContext [-Connection ] [] ``` ## DESCRIPTION -Returns a Client Side Object Model context +Returns a SharePoint Online Client Side Object Model (CSOM) context ## EXAMPLES @@ -43,8 +43,20 @@ Get-PnPList # returns the lists from site A ## PARAMETERS -## RELATED LINKS +### -Connection +Optional connection to be used by the cmdlet. Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection. If not provided, the context of the connection will be retrieved from the current connection. + +```yaml +Type: PnPConnection +Parameter Sets: (All) -[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) +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-PnPList.md b/documentation/Get-PnPList.md index 77797c022..8a538c751 100644 --- a/documentation/Get-PnPList.md +++ b/documentation/Get-PnPList.md @@ -53,20 +53,6 @@ This examples shows how to do wildcard searches on the list URL. It returns all ## PARAMETERS -### -Connection -Optional connection to be used by the cmdlet. Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection. - -```yaml -Type: PnPConnection -Parameter Sets: (All) - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### -Identity The ID, name or Url (Lists/MyList) of the list @@ -95,10 +81,20 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Connection +Optional connection to be used by the cmdlet. Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection. +```yaml +Type: PnPConnection +Parameter Sets: (All) -## RELATED LINKS - -[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) +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/src/Commands/Base/BasePSCmdlet.cs b/src/Commands/Base/BasePSCmdlet.cs index ef31875c7..f16d0927c 100644 --- a/src/Commands/Base/BasePSCmdlet.cs +++ b/src/Commands/Base/BasePSCmdlet.cs @@ -1,10 +1,5 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Linq.Expressions; using System.Management.Automation; -using System.Reflection; using PnP.PowerShell.Commands.Attributes; namespace PnP.PowerShell.Commands.Base diff --git a/src/Commands/Base/ConnectOnline.cs b/src/Commands/Base/ConnectOnline.cs index ad43c8597..2c600674b 100644 --- a/src/Commands/Base/ConnectOnline.cs +++ b/src/Commands/Base/ConnectOnline.cs @@ -283,8 +283,8 @@ protected void Connect(ref CancellationToken cancellationToken) #else WriteVerbose($"PnP PowerShell Cmdlets ({Assembly.GetExecutingAssembly().GetName().Version})"); #endif - PnPConnection.Current = connection; - if (CreateDrive && PnPConnection.Current.Context != null) + + if (CreateDrive && connection.Context != null) { var provider = SessionState.Provider.GetAll().FirstOrDefault(p => p.Name.Equals(SPOProvider.PSProviderName, StringComparison.InvariantCultureIgnoreCase)); if (provider != null) @@ -299,9 +299,9 @@ protected void Connect(ref CancellationToken cancellationToken) } } - if (PnPConnection.Current.Url != null) + if (connection.Url != null) { - var hostUri = new Uri(PnPConnection.Current.Url); + var hostUri = new Uri(connection.Url); Environment.SetEnvironmentVariable("PNPPSHOST", hostUri.Host); Environment.SetEnvironmentVariable("PNPPSSITE", hostUri.LocalPath); } @@ -315,7 +315,10 @@ protected void Connect(ref CancellationToken cancellationToken) { WriteObject(connection); } - + else + { + PnPConnection.Current = connection; + } } #region Connect Types diff --git a/src/Commands/Base/DisconnectOnline.cs b/src/Commands/Base/DisconnectOnline.cs index 5d8c837a5..c611a82f2 100644 --- a/src/Commands/Base/DisconnectOnline.cs +++ b/src/Commands/Base/DisconnectOnline.cs @@ -4,7 +4,6 @@ using System.Management.Automation; using System.Reflection; using PnP.PowerShell.Commands.Provider; -using PnP.PowerShell.Commands.Model; namespace PnP.PowerShell.Commands.Base { @@ -18,35 +17,24 @@ public class DisconnectOnline : PSCmdlet protected override void ProcessRecord() { // If no specific connection has been passed in, take the connection from the current context - if (Connection == null) - { - Connection = PnPConnection.Current; - } - if (Connection?.Certificate != null) + var connection = Connection ?? PnPConnection.Current; + + if (connection?.Certificate != null) { - if (Connection != null && Connection.DeleteCertificateFromCacheOnDisconnect) + if (connection != null && connection.DeleteCertificateFromCacheOnDisconnect) { - PnPConnection.CleanupCryptoMachineKey(Connection.Certificate); + PnPConnection.CleanupCryptoMachineKey(connection.Certificate); } - Connection.Certificate = null; - } - var success = false; - if (Connection != null) - { - success = DisconnectProvidedService(Connection); - } - else - { - success = DisconnectCurrentService(); + connection.Certificate = null; } + + var success = DisconnectProvidedService(ref connection); + if (!success) { throw new InvalidOperationException(Properties.Resources.NoConnectionToDisconnect); } - // clear credentials - PnPConnection.Current = null; - var provider = SessionState.Provider.GetAll().FirstOrDefault(p => p.Name.Equals(SPOProvider.PSProviderName, StringComparison.InvariantCultureIgnoreCase)); if (provider != null) { @@ -59,7 +47,7 @@ protected override void ProcessRecord() } } - internal static bool DisconnectProvidedService(PnPConnection connection) + internal static bool DisconnectProvidedService(ref PnPConnection connection) { Environment.SetEnvironmentVariable("PNPPSHOST", string.Empty); Environment.SetEnvironmentVariable("PNPPSSITE", string.Empty); @@ -71,22 +59,5 @@ internal static bool DisconnectProvidedService(PnPConnection connection) connection = null; return true; } - - internal static bool DisconnectCurrentService() - { - Environment.SetEnvironmentVariable("PNPPSHOST", string.Empty); - Environment.SetEnvironmentVariable("PNPPSSITE", string.Empty); - - if (PnPConnection.Current == null) - { - return false; - } - else - { - PnPConnection.Current.Context = null; - PnPConnection.Current = null; - return true; - } - } } -} +} \ No newline at end of file diff --git a/src/Commands/Base/GetConnection.cs b/src/Commands/Base/GetConnection.cs index 97beff965..cd05c3f94 100644 --- a/src/Commands/Base/GetConnection.cs +++ b/src/Commands/Base/GetConnection.cs @@ -1,32 +1,14 @@ using System.Management.Automation; -using System; -using PnP.PowerShell.Commands.Properties; - namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Get, "PnPConnection")] [OutputType(typeof(PnPConnection))] - public class GetPnPConnection : PSCmdlet + public class GetPnPConnection : PnPSharePointCmdlet { - - protected override void BeginProcessing() - { - base.BeginProcessing(); - - if (PnPConnection.Current == null) - { - throw new InvalidOperationException(Resources.NoSharePointConnection); - } - if (PnPConnection.Current.Context == null) - { - throw new InvalidOperationException(Resources.NoSharePointConnection); - } - } - protected override void ProcessRecord() { - WriteObject(PnPConnection.Current); + WriteObject(Connection); } } -} +} \ No newline at end of file diff --git a/src/Commands/Base/GetContext.cs b/src/Commands/Base/GetContext.cs index 0c5b08f84..6e45652fd 100644 --- a/src/Commands/Base/GetContext.cs +++ b/src/Commands/Base/GetContext.cs @@ -1,32 +1,14 @@ using System.Management.Automation; -using System; -using PnP.PowerShell.Commands.Properties; - namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Get, "PnPContext")] [OutputType(typeof(Microsoft.SharePoint.Client.ClientContext))] - public class GetSPOContext : PSCmdlet + public class GetSPOContext : PnPSharePointCmdlet { - - protected override void BeginProcessing() - { - base.BeginProcessing(); - - if (PnPConnection.Current == null) - { - throw new InvalidOperationException(Resources.NoSharePointConnection); - } - if (PnPConnection.Current.Context == null) - { - throw new InvalidOperationException(Resources.NoSharePointConnection); - } - } - protected override void ProcessRecord() { - WriteObject(PnPConnection.Current.Context); + WriteObject(Connection.Context); } } -} +} \ No newline at end of file diff --git a/src/Commands/Base/PnPConnectedCmdlet.cs b/src/Commands/Base/PnPConnectedCmdlet.cs index 9feabbd78..c6b5eb630 100644 --- a/src/Commands/Base/PnPConnectedCmdlet.cs +++ b/src/Commands/Base/PnPConnectedCmdlet.cs @@ -1,5 +1,4 @@ using System; -using System.Management.Automation; using System.Net.Http; namespace PnP.PowerShell.Commands.Base @@ -10,9 +9,17 @@ namespace PnP.PowerShell.Commands.Base public abstract class PnPConnectedCmdlet : BasePSCmdlet { protected override void BeginProcessing() + { + BeginProcessing(false); + } + + protected void BeginProcessing(bool skipConnectedValidation) { base.BeginProcessing(); + // Check if we should ensure that we are connected + if(skipConnectedValidation) return; + // Ensure there is an active connection if (PnPConnection.Current == null) { @@ -21,9 +28,5 @@ protected override void BeginProcessing() } public HttpClient HttpClient => PnP.Framework.Http.PnPHttpClient.Instance.GetHttpClient(); - - } - - } diff --git a/src/Commands/Base/PnPConnection.cs b/src/Commands/Base/PnPConnection.cs index 2bf5115d3..985ffd856 100644 --- a/src/Commands/Base/PnPConnection.cs +++ b/src/Commands/Base/PnPConnection.cs @@ -611,6 +611,8 @@ internal void RestoreCachedContext(string url) internal void CacheContext() { + if(Context == null) return; + var c = ContextCache.FirstOrDefault(cc => new Uri(cc.Url).AbsoluteUri == new Uri(Context.Url).AbsoluteUri); if (c == null) { diff --git a/src/Commands/Base/PnPSharePointCmdlet.cs b/src/Commands/Base/PnPSharePointCmdlet.cs index 49e02fc53..42a6cce56 100644 --- a/src/Commands/Base/PnPSharePointCmdlet.cs +++ b/src/Commands/Base/PnPSharePointCmdlet.cs @@ -20,9 +20,9 @@ public abstract class PnPSharePointCmdlet : PnPConnectedCmdlet /// /// Reference the the SharePoint context on the current connection. If NULL it means there is no SharePoint context available on the current connection. /// - public ClientContext ClientContext => Connection?.Context ?? PnPConnection.Current.Context; + public ClientContext ClientContext => Connection?.Context; - public PnPContext PnPContext => Connection?.PnPContext ?? PnPConnection.Current.PnPContext; + public PnPContext PnPContext => Connection?.PnPContext ?? Connection.PnPContext; public new HttpClient HttpClient => PnP.Framework.Http.PnPHttpClient.Instance.GetHttpClient(ClientContext); @@ -33,14 +33,23 @@ public abstract class PnPSharePointCmdlet : PnPConnectedCmdlet protected override void BeginProcessing() { - base.BeginProcessing(); + // Call the base but instruct it not to check if there's an active connection as we will do that in this method already + base.BeginProcessing(true); - if (PnPConnection.Current != null && PnPConnection.Current.ApplicationInsights != null) + // If a specific connection has been provided, use that, otherwise use the current connection + if(Connection == null) { - PnPConnection.Current.ApplicationInsights.TrackEvent(MyInvocation.MyCommand.Name); + Connection = PnPConnection.Current; } - if (Connection == null && ClientContext == null) + // Track the execution of the cmdlet + if (Connection != null && Connection.ApplicationInsights != null) + { + Connection.ApplicationInsights.TrackEvent(MyInvocation.MyCommand.Name); + } + + // Ensure there is an active connection to work with + if (Connection == null || ClientContext == null) { throw new InvalidOperationException(Resources.NoSharePointConnection); } @@ -50,7 +59,7 @@ protected override void ProcessRecord() { try { - var tag = PnPConnection.Current.PnPVersionTag + ":" + MyInvocation.MyCommand.Name; + var tag = Connection.PnPVersionTag + ":" + MyInvocation.MyCommand.Name; if (tag.Length > 32) { tag = tag.Substring(0, 32); @@ -75,8 +84,8 @@ protected override void ProcessRecord() } catch (Exception ex) { - PnPConnection.Current.RestoreCachedContext(PnPConnection.Current.Url); - ex.Data["CorrelationId"] = PnPConnection.Current.Context.TraceCorrelationId; + Connection.RestoreCachedContext(Connection.Url); + ex.Data["CorrelationId"] = Connection.Context.TraceCorrelationId; ex.Data["TimeStampUtc"] = DateTime.UtcNow; var errorDetails = new ErrorDetails(ex.Message); @@ -97,17 +106,17 @@ protected string AccessToken { get { - if (PnPConnection.Current != null) + if (Connection != null) { - if (PnPConnection.Current.Context != null) + if (Connection.Context != null) { - var settings = Microsoft.SharePoint.Client.InternalClientContextExtensions.GetContextSettings(PnPConnection.Current.Context); + var settings = Microsoft.SharePoint.Client.InternalClientContextExtensions.GetContextSettings(Connection.Context); if (settings != null) { var authManager = settings.AuthenticationManager; if (authManager != null) { - return authManager.GetAccessTokenAsync(PnPConnection.Current.Context.Url).GetAwaiter().GetResult(); + return authManager.GetAccessTokenAsync(Connection.Context.Url).GetAwaiter().GetResult(); } } } @@ -120,15 +129,15 @@ public string GraphAccessToken { get { - if (PnPConnection.Current?.ConnectionMethod == ConnectionMethod.ManagedIdentity) + if (Connection?.ConnectionMethod == ConnectionMethod.ManagedIdentity) { return TokenHandler.GetManagedIdentityTokenAsync(this, HttpClient, $"https://graph.microsoft.com/").GetAwaiter().GetResult(); } else { - if (PnPConnection.Current?.Context != null) + if (Connection?.Context != null) { - return TokenHandler.GetAccessToken(GetType(), $"https://{PnPConnection.Current.GraphEndPoint}/.default"); + return TokenHandler.GetAccessToken(GetType(), $"https://{Connection.GraphEndPoint}/.default"); } } diff --git a/src/Commands/Base/PnPWebRetrievalsCmdlet.cs b/src/Commands/Base/PnPWebRetrievalsCmdlet.cs index f447b6861..7b7e8e50d 100644 --- a/src/Commands/Base/PnPWebRetrievalsCmdlet.cs +++ b/src/Commands/Base/PnPWebRetrievalsCmdlet.cs @@ -4,8 +4,6 @@ using System.Management.Automation; using Microsoft.SharePoint.Client; -using PnP.PowerShell.Commands.Extensions; - namespace PnP.PowerShell.Commands { /// @@ -41,20 +39,20 @@ private Web GetWeb() { var subWeb = Web.GetWeb(ClientContext); subWeb.EnsureProperty(w => w.Url); - PnPConnection.Current.CloneContext(subWeb.Url); - web = PnPConnection.Current.Context.Web; + Connection.CloneContext(subWeb.Url); + web = Connection.Context.Web; } #pragma warning restore CS0618 else { - if (PnPConnection.Current.Context.Url != PnPConnection.Current.Url) + if (Connection.Context.Url != Connection.Url) { - PnPConnection.Current.RestoreCachedContext(PnPConnection.Current.Url); + Connection.RestoreCachedContext(Connection.Url); } web = ClientContext.Web; } - PnPConnection.Current.Context.ExecuteQueryRetry(); + Connection.Context.ExecuteQueryRetry(); return web; } @@ -62,16 +60,16 @@ private Web GetWeb() protected override void EndProcessing() { base.EndProcessing(); - if (PnPConnection.Current.Context.Url != PnPConnection.Current.Url) + if (Connection.Context.Url != Connection.Url) { - PnPConnection.Current.RestoreCachedContext(PnPConnection.Current.Url); + Connection.RestoreCachedContext(Connection.Url); } } protected override void BeginProcessing() { base.BeginProcessing(); - PnPConnection.Current.CacheContext(); + Connection.CacheContext(); } } } \ No newline at end of file From 9babaa8a0cbd5d6f64300cda48260397d93b4c20 Mon Sep 17 00:00:00 2001 From: Koen Zomers Date: Tue, 31 May 2022 22:56:04 +0200 Subject: [PATCH 2/6] Added PR reference --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa3757b8..0b157b566 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Added capability to Debug the module in Visual Studio. [#1880](https://github.com/pnp/powershell/pull/1880) - Added `Set-PnPTeamsChannelUser` cmdlet to update the role of user in a private channel. [#1865](https://github.com/pnp/powershell/pull/1865) - Added `Restart-PnPFlowRun` which allows for a failed Power Automate flow run to be retried [#1915](https://github.com/pnp/powershell/pull/1915) +- Added optional `-Connection` parameter to `Get-PnPConnection` and `Get-PnPContext` which allows for retrieving both of these for a specific connection [#1919](https://github.com/pnp/powershell/pull/1919) ### Changed - Changed `Sync-PnPSharePointUserProfilesFromAzureActiveDirectory` to map users based on their Ids instead which should resolve some issues around user identities reporting not to exist. You can use the new `-IdType` option to switch it back to `PrincipalName` if needed. [#1752](https://github.com/pnp/powershell/pull/1752) @@ -58,8 +59,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Fixed `Invoke-PnPSPRestMethod` invalid parsing for SharePoint number columns. [#1877](https://github.com/pnp/powershell/pull/1879) - Fix issue with `Add/Set-PnPListItem` not throwing correct exception for invalid taxonomy values. [#1870](https://github.com/pnp/powershell/pull/1870) - Fixed `Sync-PnPSharePointUserProfilesFromAzureActiveDirectory` throwing an "Object reference not set to an instance of an object" exception when providing an empty users collection or incorrect user mapping [#1896](https://github.com/pnp/powershell/pull/1896) -- Fixed `Connect-PnPOnline -ReturnConnection` also setting the current connection instead of just the returned connection -- Fixed `Disconnect-PnPOnline -Connection` also disconnecting other connections next to the provided connection +- Fixed `Connect-PnPOnline -ReturnConnection` also setting the current connection instead of just the returned connection [#1919](https://github.com/pnp/powershell/pull/1919 +- Fixed `Disconnect-PnPOnline -Connection` also disconnecting other connections next to the provided connection [#1919](https://github.com/pnp/powershell/pull/1919 ### Removed - Removed `Get-PnPAvailableClientSideComponents`. Use `Get-PnPPageComponent -Page -ListAvailable` instead. [#1833](https://github.com/pnp/powershell/pull/1833) From f1b4e6f64e5c9f892ba827a82311871901825c39 Mon Sep 17 00:00:00 2001 From: Koen Zomers Date: Tue, 31 May 2022 22:56:19 +0200 Subject: [PATCH 3/6] Fixed build validation issue --- documentation/Get-PnPConnection.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/documentation/Get-PnPConnection.md b/documentation/Get-PnPConnection.md index c67553c36..1a54d466d 100644 --- a/documentation/Get-PnPConnection.md +++ b/documentation/Get-PnPConnection.md @@ -35,8 +35,6 @@ This will put the current connection for use with the -Connection parameter on o ### -Connection Optional connection to be used by the cmdlet. Retrieve the value for this parameter by specifying -ReturnConnection on Connect-PnPOnline. If not provided, the connection will be retrieved from the current context. -```yaml - ```yaml Type: PnPConnection Parameter Sets: (All) From 99e18703c455643e7ea9921db227615d06b9b775 Mon Sep 17 00:00:00 2001 From: Koen Zomers Date: Tue, 31 May 2022 23:28:53 +0200 Subject: [PATCH 4/6] Fix for issue #1729 --- documentation/Set-PnPContext.md | 21 +++++++++++++++++---- src/Commands/Base/PnPWebRetrievalsCmdlet.cs | 5 +++-- src/Commands/Base/SetContext.cs | 7 +++---- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/documentation/Set-PnPContext.md b/documentation/Set-PnPContext.md index ea5077b4b..0eebc9454 100644 --- a/documentation/Set-PnPContext.md +++ b/documentation/Set-PnPContext.md @@ -15,11 +15,11 @@ Set the ClientContext ## SYNTAX ```powershell -Set-PnPContext [-Context] [] +Set-PnPContext -Context [-Connection ] [] ``` ## DESCRIPTION -Sets the Client Context to use by the cmdlets, which allows easy context switching. See examples for details. +Sets the Client Context to be used by the cmdlets, which allows easy context switching. See examples for details. ## EXAMPLES @@ -50,7 +50,20 @@ Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` -## RELATED LINKS +### -Connection +Optional connection to be used by the cmdlet. Retrieve the value for this parameter by specifying -ReturnConnection on Connect-PnPOnline. If not provided, the connection will be retrieved from the current context. -[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) +```yaml +Type: PnPConnection +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/src/Commands/Base/PnPWebRetrievalsCmdlet.cs b/src/Commands/Base/PnPWebRetrievalsCmdlet.cs index 7b7e8e50d..1bd16968a 100644 --- a/src/Commands/Base/PnPWebRetrievalsCmdlet.cs +++ b/src/Commands/Base/PnPWebRetrievalsCmdlet.cs @@ -1,5 +1,4 @@ using System; -using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using System.Management.Automation; using Microsoft.SharePoint.Client; @@ -45,9 +44,11 @@ private Web GetWeb() #pragma warning restore CS0618 else { + // Validate that our ClientContext and PnPConnection are both for the same site if (Connection.Context.Url != Connection.Url) { - Connection.RestoreCachedContext(Connection.Url); + // ClientContext is for a different site than our PnPConnection, try to make the connection match the ClientContext URL + Connection.RestoreCachedContext(Connection.Context.Url); } web = ClientContext.Web; } diff --git a/src/Commands/Base/SetContext.cs b/src/Commands/Base/SetContext.cs index 7f9c03758..4ba675848 100644 --- a/src/Commands/Base/SetContext.cs +++ b/src/Commands/Base/SetContext.cs @@ -1,18 +1,17 @@ using System.Management.Automation; - using Microsoft.SharePoint.Client; namespace PnP.PowerShell.Commands.Base { [Cmdlet(VerbsCommon.Set, "PnPContext")] - public class SetContext : PSCmdlet + public class SetContext : PnPSharePointCmdlet { [Parameter(Mandatory = true, ValueFromPipeline = true, Position = 1)] public ClientContext Context; protected override void ProcessRecord() { - PnPConnection.Current.Context = Context; + Connection.Context = Context; } } -} +} \ No newline at end of file From b74aad7b7a3c9bb58ab2e5243c6a3000e3c9fcb0 Mon Sep 17 00:00:00 2001 From: Koen Zomers Date: Tue, 31 May 2022 23:31:24 +0200 Subject: [PATCH 5/6] Added changelog entry for the fix for issue #1729 --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcf4a87f7..237548855 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,7 +36,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Added capability to Debug the module in Visual Studio. [#1880](https://github.com/pnp/powershell/pull/1880) - Added `Set-PnPTeamsChannelUser` cmdlet to update the role of user in a private channel. [#1865](https://github.com/pnp/powershell/pull/1865) - Added `Restart-PnPFlowRun` which allows for a failed Power Automate flow run to be retried [#1915](https://github.com/pnp/powershell/pull/1915) -- Added optional `-Connection` parameter to `Get-PnPConnection` and `Get-PnPContext` which allows for retrieving both of these for a specific connection [#1919](https://github.com/pnp/powershell/pull/1919) +- Added optional `-Connection` parameter to `Get-PnPConnection`, `Get-PnPContext` and `Set-PnPContext` which allows for retrieving both of these for a specific connection [#1919](https://github.com/pnp/powershell/pull/1919) - Added `-IncludeDeprecated` parameter to `Get-PnPTerm` cmdlet to fetch deprecated terms if specified [#1903](https://github.com/pnp/powershell/pull/1903) ### Changed @@ -60,8 +60,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Fixed `Invoke-PnPSPRestMethod` invalid parsing for SharePoint number columns. [#1877](https://github.com/pnp/powershell/pull/1879) - Fix issue with `Add/Set-PnPListItem` not throwing correct exception for invalid taxonomy values. [#1870](https://github.com/pnp/powershell/pull/1870) - Fixed `Sync-PnPSharePointUserProfilesFromAzureActiveDirectory` throwing an "Object reference not set to an instance of an object" exception when providing an empty users collection or incorrect user mapping [#1896](https://github.com/pnp/powershell/pull/1896) -- Fixed `Connect-PnPOnline -ReturnConnection` also setting the current connection instead of just the returned connection [#1919](https://github.com/pnp/powershell/pull/1919 -- Fixed `Disconnect-PnPOnline -Connection` also disconnecting other connections next to the provided connection [#1919](https://github.com/pnp/powershell/pull/1919 +- Fixed `Connect-PnPOnline -ReturnConnection` also setting the current connection instead of just the returned connection [#1919](https://github.com/pnp/powershell/pull/1919) +- Fixed `Disconnect-PnPOnline -Connection` also disconnecting other connections next to the provided connection [#1919](https://github.com/pnp/powershell/pull/1919) +- Fixed `Set-PnPContext` not properly applying the provided context [#1919](https://github.com/pnp/powershell/pull/1919) ### Removed - Removed `Get-PnPAvailableClientSideComponents`. Use `Get-PnPPageComponent -Page -ListAvailable` instead. [#1833](https://github.com/pnp/powershell/pull/1833) From cafeb0a4165ce06ebeab56ca8f610fa8014921fd Mon Sep 17 00:00:00 2001 From: Koen Zomers Date: Wed, 1 Jun 2022 09:01:21 +0200 Subject: [PATCH 6/6] Update CHANGELOG.md Wording fix --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 237548855..61a4680db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,7 +36,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Added capability to Debug the module in Visual Studio. [#1880](https://github.com/pnp/powershell/pull/1880) - Added `Set-PnPTeamsChannelUser` cmdlet to update the role of user in a private channel. [#1865](https://github.com/pnp/powershell/pull/1865) - Added `Restart-PnPFlowRun` which allows for a failed Power Automate flow run to be retried [#1915](https://github.com/pnp/powershell/pull/1915) -- Added optional `-Connection` parameter to `Get-PnPConnection`, `Get-PnPContext` and `Set-PnPContext` which allows for retrieving both of these for a specific connection [#1919](https://github.com/pnp/powershell/pull/1919) +- Added optional `-Connection` parameter to `Get-PnPConnection`, `Get-PnPContext` and `Set-PnPContext` which allows for using any of these for a specific connection [#1919](https://github.com/pnp/powershell/pull/1919) - Added `-IncludeDeprecated` parameter to `Get-PnPTerm` cmdlet to fetch deprecated terms if specified [#1903](https://github.com/pnp/powershell/pull/1903) ### Changed