From ce4d55911ff884ec045a181e065314fa8fe9dc40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:39:31 +0200 Subject: [PATCH 01/60] Return path override if present --- src/code/Utils.cs | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index e2dc8406c..a8949b8ff 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -995,24 +995,35 @@ public static List GetPathsFromEnvVarAndScope( PSCmdlet psCmdlet, ScopeType? scope) { - GetStandardPlatformPaths( - psCmdlet, - out string myDocumentsPath, - out string programFilesPath); - - List resourcePaths = new List(); - if (scope is null || scope.Value is ScopeType.CurrentUser) - { - resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); - resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); - } - - if (scope.Value is ScopeType.AllUsers) - { - resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); - resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); + // Assets + List resourcePaths = new(); + string pathOverride = Environment.GetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User + ); + // Return override if present, else default paths + if (!string.IsNullOrEmpty(pathOverride) && Directory.Exists(pathOverride)) + { + resourcePaths.Add(Path.Combine(pathOverride, "Modules")); + resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); + } + else { + GetStandardPlatformPaths( + psCmdlet, + out string myDocumentsPath, + out string programFilesPath + ); + if (scope.Value is ScopeType.AllUsers) + { + resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); + resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); + } + else + { + resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); + resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); + } } - return resourcePaths; } From 166bf07b23c78a88773cd90705aa3a44f51165e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:48:22 +0200 Subject: [PATCH 02/60] Make more robust --- src/code/Utils.cs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index a8949b8ff..13015cecc 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -997,11 +997,30 @@ public static List GetPathsFromEnvVarAndScope( { // Assets List resourcePaths = new(); - string pathOverride = Environment.GetEnvironmentVariable( - "PSResourceGetInstallPathOverride", - (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User - ); - // Return override if present, else default paths + string pathOverride = string.Empty; + // To to get path override + try + { + pathOverride = Environment.GetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User + ); + } + catch { + psCmdlet.WriteVerbose("Path override was not found."); + } + // Try to resolve path override + if (!string.IsNullOrEmpty(pathOverride)) { + try + { + pathOverride = Path.GetFullPath(pathOverride); + } + catch + { + psCmdlet.WriteVerbose("Path override was found, but could not be resolved to full path."); + } + } + // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Directory.Exists(pathOverride)) { resourcePaths.Add(Path.Combine(pathOverride, "Modules")); From 37417dee37701e60d593a648b073c2b2a5666bf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:50:18 +0200 Subject: [PATCH 03/60] Get empty/non-existent env variable is not expected to throw --- src/code/Utils.cs | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 13015cecc..edef7c496 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -997,18 +997,11 @@ public static List GetPathsFromEnvVarAndScope( { // Assets List resourcePaths = new(); - string pathOverride = string.Empty; - // To to get path override - try - { - pathOverride = Environment.GetEnvironmentVariable( - "PSResourceGetInstallPathOverride", - (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User - ); - } - catch { - psCmdlet.WriteVerbose("Path override was not found."); - } + // Get value of path override environment variable + string pathOverride = Environment.GetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User + ); // Try to resolve path override if (!string.IsNullOrEmpty(pathOverride)) { try From de08199ece993e589b77f6fb2c4a25a6296dbb9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:52:34 +0200 Subject: [PATCH 04/60] More robust --- src/code/Utils.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index edef7c496..066768d68 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -1008,8 +1008,9 @@ public static List GetPathsFromEnvVarAndScope( { pathOverride = Path.GetFullPath(pathOverride); } - catch + catch (ArgumentException) { + pathOverride = string.Empty; psCmdlet.WriteVerbose("Path override was found, but could not be resolved to full path."); } } From acecb75071fe14ee949df5033535c274669e1b61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 14:04:00 +0200 Subject: [PATCH 05/60] Expand, not resolve --- src/code/Utils.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 066768d68..8f1feb354 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -1002,20 +1002,20 @@ public static List GetPathsFromEnvVarAndScope( "PSResourceGetInstallPathOverride", (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User ); - // Try to resolve path override + // Try to expand path override if (!string.IsNullOrEmpty(pathOverride)) { try { - pathOverride = Path.GetFullPath(pathOverride); + pathOverride = Environment.ExpandEnvironmentVariables(pathOverride); } catch (ArgumentException) { pathOverride = string.Empty; - psCmdlet.WriteVerbose("Path override was found, but could not be resolved to full path."); + psCmdlet.WriteVerbose("Path override was found, but could not expand environment variable(s)."); } } // Return override if present, else use default paths - if (!string.IsNullOrEmpty(pathOverride) && Directory.Exists(pathOverride)) + if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { resourcePaths.Add(Path.Combine(pathOverride, "Modules")); resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); From 2713e4f25ce59437224a3864b5bba3fd344bf0ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 14:12:57 +0200 Subject: [PATCH 06/60] Add verbose message --- src/code/Utils.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 8f1feb354..78aa605a7 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -1017,6 +1017,7 @@ public static List GetPathsFromEnvVarAndScope( // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { + psCmdlet.WriteVerbose(string.Format("Path override was found, using '{0}' as base.",pathOverride)); resourcePaths.Add(Path.Combine(pathOverride, "Modules")); resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); } From 3556f802f4292e4e920b2783702f70d3e93203fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 17:12:47 +0200 Subject: [PATCH 07/60] Don't get paths twice --- src/code/InstallPSResource.cs | 38 +++++++++++++++++------------------ 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/code/InstallPSResource.cs b/src/code/InstallPSResource.cs index a65797268..67917ca78 100644 --- a/src/code/InstallPSResource.cs +++ b/src/code/InstallPSResource.cs @@ -17,15 +17,15 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets /// The Install-PSResource cmdlet installs a resource. /// It returns nothing. /// - [Cmdlet(VerbsLifecycle.Install, - "PSResource", - DefaultParameterSetName = "NameParameterSet", + [Cmdlet(VerbsLifecycle.Install, + "PSResource", + DefaultParameterSetName = "NameParameterSet", SupportsShouldProcess = true)] [Alias("isres")] public sealed class InstallPSResource : PSCmdlet { - #region Parameters + #region Parameters /// /// Specifies the exact names of resources to install from a repository. @@ -42,7 +42,7 @@ class InstallPSResource : PSCmdlet [Parameter(ParameterSetName = NameParameterSet, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string Version { get; set; } - + /// /// Specifies to allow installation of prerelease versions /// @@ -83,9 +83,9 @@ public string TemporaryPath set { - if (WildcardPattern.ContainsWildcardCharacters(value)) - { - throw new PSArgumentException("Wildcard characters are not allowed in the temporary path."); + if (WildcardPattern.ContainsWildcardCharacters(value)) + { + throw new PSArgumentException("Wildcard characters are not allowed in the temporary path."); } // This will throw if path cannot be resolved @@ -99,7 +99,7 @@ public string TemporaryPath /// [Parameter] public SwitchParameter TrustRepository { get; set; } - + /// /// Overwrites a previously installed resource with the same name and version. /// @@ -130,7 +130,7 @@ public string TemporaryPath /// [Parameter] public SwitchParameter SkipDependencyCheck { get; set; } - + /// /// Check validation for signed and catalog files /// @@ -265,7 +265,7 @@ protected override void BeginProcessing() RepositorySettings.CheckRepositoryStore(); _pathsToInstallPkg = Utils.GetAllInstallationPaths(this, Scope); - List pathsToSearch = Utils.GetAllResourcePaths(this, Scope); + List pathsToSearch = _pathsToInstallPkg; // Only need to find packages installed if -Reinstall is not passed in _packagesOnMachine = Reinstall ? new HashSet(StringComparer.CurrentCultureIgnoreCase) : Utils.GetInstalledPackages(pathsToSearch, this); @@ -287,7 +287,7 @@ protected override void ProcessRecord() pkgCredential: Credential, reqResourceParams: null); break; - + case InputObjectParameterSet: foreach (var inputObj in InputObject) { string normalizedVersionString = Utils.GetNormalizedVersionString(inputObj.Version.ToString(), inputObj.Prerelease); @@ -362,7 +362,7 @@ protected override void ProcessRecord() ErrorCategory.InvalidData, this)); } - + RequiredResourceHelper(pkgsInFile); break; @@ -379,7 +379,7 @@ protected override void ProcessRecord() } } */ - + Hashtable pkgsHash = null; try { @@ -441,7 +441,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) { var pkgNameEmptyOrWhitespaceError = new ErrorRecord( new ArgumentException($"The package name '{pkgName}' provided cannot be an empty string or whitespace."), - "pkgNameEmptyOrWhitespaceError", + "pkgNameEmptyOrWhitespaceError", ErrorCategory.InvalidArgument, this); @@ -454,7 +454,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) { var requiredResourceHashtableInputFormatError = new ErrorRecord( new ArgumentException($"The RequiredResource input with name '{pkgName}' does not have a valid value, the value must be a hashtable."), - "RequiredResourceHashtableInputFormatError", + "RequiredResourceHashtableInputFormatError", ErrorCategory.InvalidArgument, this); @@ -483,7 +483,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) ThrowTerminatingError(ParameterParsingError); } } - + if (pkgParams.Scope == ScopeType.AllUsers) { _pathsToInstallPkg = Utils.GetAllInstallationPaths(this, pkgParams.Scope); @@ -513,10 +513,10 @@ private void ProcessInstallHelper(string[] pkgNames, string pkgVersion, bool pkg "NameContainsWildcard", ErrorCategory.InvalidArgument, this)); - + return; } - + foreach (string error in errorMsgs) { WriteError(new ErrorRecord( From f3abadd7f8751a0b1c98d7a33bab35a55b5ef30e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 17:13:09 +0200 Subject: [PATCH 08/60] Add newline before comments --- src/code/Utils.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 78aa605a7..0bb1e6df5 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -997,11 +997,13 @@ public static List GetPathsFromEnvVarAndScope( { // Assets List resourcePaths = new(); + // Get value of path override environment variable string pathOverride = Environment.GetEnvironmentVariable( "PSResourceGetInstallPathOverride", (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User ); + // Try to expand path override if (!string.IsNullOrEmpty(pathOverride)) { try @@ -1014,6 +1016,7 @@ public static List GetPathsFromEnvVarAndScope( psCmdlet.WriteVerbose("Path override was found, but could not expand environment variable(s)."); } } + // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { @@ -1038,6 +1041,8 @@ out string programFilesPath resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); } } + + // Return results return resourcePaths; } From 49db4bb41ce913a556a55c024e2973f335a6748c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 11:51:47 +0200 Subject: [PATCH 09/60] Remove empty newline --- src/code/GetInstalledPSResource.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/code/GetInstalledPSResource.cs b/src/code/GetInstalledPSResource.cs index dafd36400..fc30d5eb6 100644 --- a/src/code/GetInstalledPSResource.cs +++ b/src/code/GetInstalledPSResource.cs @@ -89,7 +89,6 @@ protected override void BeginProcessing() { ThrowTerminatingError(new ErrorRecord( new PSArgumentException($"Error: Could not resolve provided Path argument '{Path}' into a single path."), - "ErrorInvalidPathArgument", ErrorCategory.InvalidArgument, this)); @@ -153,7 +152,7 @@ protected override void ProcessRecord() List pkgsNotFound = new List(); foreach (string name in namesToSearch) { - if (!pkgsFound.Contains(name, StringComparer.OrdinalIgnoreCase)) + if (!pkgsFound.Contains(name, StringComparer.OrdinalIgnoreCase)) { if (name.Contains('*')) { From 802184e202d1bdb06cf6771074596c39b01b13a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 12:04:32 +0200 Subject: [PATCH 10/60] Added new cmdlet --- src/Microsoft.PowerShell.PSResourceGet.psd1 | 25 ++++--- .../SetPSResourceGetInstallPathOverride.cs | 70 +++++++++++++++++++ 2 files changed, 84 insertions(+), 11 deletions(-) create mode 100644 src/code/SetPSResourceGetInstallPathOverride.cs diff --git a/src/Microsoft.PowerShell.PSResourceGet.psd1 b/src/Microsoft.PowerShell.PSResourceGet.psd1 index b5abe9ae6..afdb7a2ac 100644 --- a/src/Microsoft.PowerShell.PSResourceGet.psd1 +++ b/src/Microsoft.PowerShell.PSResourceGet.psd1 @@ -21,29 +21,32 @@ 'Get-PSResourceRepository', 'Get-PSScriptFileInfo', 'Install-PSResource', + 'New-PSScriptFileInfo', + 'Publish-PSResource', 'Register-PSResourceRepository', 'Save-PSResource', + 'Set-PSResourceGetInstallPathOverride', 'Set-PSResourceRepository', - 'New-PSScriptFileInfo', 'Test-PSScriptFileInfo', - 'Update-PSScriptFileInfo', - 'Publish-PSResource', 'Uninstall-PSResource', 'Unregister-PSResourceRepository', 'Update-PSModuleManifest', - 'Update-PSResource' + 'Update-PSResource', + 'Update-PSScriptFileInfo' ) FunctionsToExport = @( 'Import-PSGetRepository' ) - VariablesToExport = 'PSGetPath' - AliasesToExport = @( + VariablesToExport = 'PSGetPath' + AliasesToExport = @( 'Get-PSResource', 'fdres', 'isres', 'pbres', - 'udres') - PrivateData = @{ + 'Update-PSResourceGetInstallPathOverride', + 'udres' + ) + PrivateData = @{ PSData = @{ Prerelease = 'preview1' Tags = @('PackageManagement', @@ -59,7 +62,7 @@ ### New Features -- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, +- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, #1573, #1576, #1587, #1588, #1589, #1594, #1598, #1600, #1602, #1604, #1615) ### Bug Fixes @@ -111,7 +114,7 @@ - Bug fix Artifactory v2 endpoint failures (#1428) - Bug fix Artifactory v3 endpoint failures (#1427) - Bug fix `-RequiredResource` silent failures (#1426) -- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) +- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) ## 0.9.0-rc1 @@ -193,7 +196,7 @@ - Improve error handling in Uninstall-PSResource (#1215) - Change resolved paths to use GetResolvedProviderPathFromPSPath (#1209) - Bug fix for Get-InstalledPSResource returning type of scripts as module (#1198) - + ## 0.5.22-beta22 diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs new file mode 100644 index 000000000..f416d82e0 --- /dev/null +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.PowerShell.PSResourceGet.UtilClasses; +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.PSResourceGet.Cmdlets +{ + /// + /// The Set-PSResourceGetInstallPathOverride cmdlet is used to override install path for PS resources. + /// + [Cmdlet(VerbsCommon.Set,"PSResourceGetInstallPathOverride",SupportsShouldProcess = true)] + [Alias("Update-PSResourceGetInstallPathOverride")] + [OutputType(typeof(void))] + + public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet + { + #region Parameters + + /// + /// Specifies the desired path for the override. + /// + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] + public string Path { get; set; } + + /// + /// Specifies the scope of installation. + /// + [Parameter(Position = 1)] + public ScopeType Scope { get; set; } + + #endregion + + #region Methods + + protected override void BeginProcessing() + { + // Validate path is not null or empty + if (string.IsNullOrEmpty(Path)) { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), + "PathMissingExpectedSubdirectories", + ErrorCategory.InvalidOperation, + this + ) + ); + } + + // Validate path is absolute + if (!System.IO.Path.IsPathRooted(Path)) { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), + "PathMissingExpectedSubdirectories", + ErrorCategory.InvalidOperation, + this + ) + ); + } + } + + protected override void ProcessRecord() + { + } + + #endregion + } +} From a6352fea4eed0f8c6e25b557f1b76484d6475c81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 12:08:43 +0200 Subject: [PATCH 11/60] "using System;" was written twice --- src/code/ServerApiCall.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/code/ServerApiCall.cs b/src/code/ServerApiCall.cs index 9f8bf4fe9..cbe429c28 100644 --- a/src/code/ServerApiCall.cs +++ b/src/code/ServerApiCall.cs @@ -2,15 +2,14 @@ // Licensed under the MIT License. using Microsoft.PowerShell.PSResourceGet.UtilClasses; +using NuGet.Versioning; using System; using System.IO; -using System.Net.Http; -using NuGet.Versioning; +using System.Management.Automation; using System.Net; -using System.Text; +using System.Net.Http; using System.Runtime.ExceptionServices; -using System.Management.Automation; -using System; +using System.Text; namespace Microsoft.PowerShell.PSResourceGet.Cmdlets { @@ -28,11 +27,11 @@ internal abstract class ServerApiCall : IServerAPICalls public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCredential) { this.Repository = repository; - + HttpClientHandler handler = new HttpClientHandler(); bool token = false; - if(networkCredential != null) + if(networkCredential != null) { token = String.Equals("token", networkCredential.UserName) ? true : false; }; @@ -47,7 +46,7 @@ public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCrede } else { handler.Credentials = networkCredential; - + _sessionClient = new HttpClient(handler); }; _sessionClient.Timeout = TimeSpan.FromMinutes(10); From 386bcf3b25786a8a2ef241e85d0640b200fcc4dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 17:52:26 +0200 Subject: [PATCH 12/60] Only for Windows because env variables is very different on Unix + Make path to returning standard paths shorter --- .../SetPSResourceGetInstallPathOverride.cs | 17 +++- src/code/Utils.cs | 78 ++++++++++++------- 2 files changed, 66 insertions(+), 29 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index f416d82e0..5d068e7b3 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -4,6 +4,7 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; using System.Management.Automation; +using System.Runtime.InteropServices; namespace Microsoft.PowerShell.PSResourceGet.Cmdlets { @@ -36,13 +37,25 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet protected override void BeginProcessing() { + // Only run on Windows for now, due to env variables on Unix being very different + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error this only works on Windows for now'"), + "PathMissingExpectedSubdirectories", + ErrorCategory.InvalidOperation, + this + ) + ); + } + // Validate path is not null or empty if (string.IsNullOrEmpty(Path)) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), "PathMissingExpectedSubdirectories", - ErrorCategory.InvalidOperation, + ErrorCategory.InvalidArgument, this ) ); @@ -54,7 +67,7 @@ protected override void BeginProcessing() new ErrorRecord( new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), "PathMissingExpectedSubdirectories", - ErrorCategory.InvalidOperation, + ErrorCategory.InvalidArgument, this ) ); diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 0bb1e6df5..ee173388a 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -990,60 +990,84 @@ public static string GetInstalledPackageName(string pkgPath) return new DirectoryInfo(pkgPath).Parent.Name; } - // Find all potential resource paths - public static List GetPathsFromEnvVarAndScope( + // Get standard install paths given scope + public static List GetStandardPathsForScope( PSCmdlet psCmdlet, ScopeType? scope) { // Assets List resourcePaths = new(); + // Get standard paths + GetStandardPlatformPaths( + psCmdlet, + out string myDocumentsPath, + out string programFilesPath + ); + + // Add paths to output + if (scope.Value is ScopeType.AllUsers) + { + resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); + resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); + } + else + { + resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); + resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); + } + + // Return results + return resourcePaths; + } + + // Find all potential resource paths + public static List GetPathsFromEnvVarAndScope( + PSCmdlet psCmdlet, + ScopeType? scope) + { + // Path override is only implemented for Windows so far + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { + return GetStandardPathsForScope(psCmdlet,scope); + } + // Get value of path override environment variable string pathOverride = Environment.GetEnvironmentVariable( "PSResourceGetInstallPathOverride", (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User ); - // Try to expand path override - if (!string.IsNullOrEmpty(pathOverride)) { + // Return standard paths if no override was found, else try to expand paths found in override + if (string.IsNullOrEmpty(pathOverride)) { + return GetStandardPathsForScope(psCmdlet,scope); + } + else { try { pathOverride = Environment.ExpandEnvironmentVariables(pathOverride); } catch (ArgumentException) { - pathOverride = string.Empty; - psCmdlet.WriteVerbose("Path override was found, but could not expand environment variable(s)."); + psCmdlet.WriteWarning("Path override was found, but could not expand environment variable(s). Falling back to standard paths."); + return GetStandardPathsForScope(psCmdlet,scope); } } // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { - psCmdlet.WriteVerbose(string.Format("Path override was found, using '{0}' as base.",pathOverride)); - resourcePaths.Add(Path.Combine(pathOverride, "Modules")); - resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); + psCmdlet.WriteVerbose(string.Format("Path override was found, using '{0}' as base.", pathOverride)); + // Assets + List resourcePaths = new() + { + Path.Combine(pathOverride, "Modules"), + Path.Combine(pathOverride, "Scripts") + }; + return resourcePaths; } else { - GetStandardPlatformPaths( - psCmdlet, - out string myDocumentsPath, - out string programFilesPath - ); - if (scope.Value is ScopeType.AllUsers) - { - resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); - resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); - } - else - { - resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); - resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); - } + return GetStandardPathsForScope(psCmdlet,scope); } - - // Return results - return resourcePaths; } public static List GetAllResourcePaths( From 6ada4c6a5557addc8e42e625bb53ddd02386ce94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 17:53:33 +0200 Subject: [PATCH 13/60] Sort using alphabetically --- src/code/Utils.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index ee173388a..8c3a07c6f 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -2,24 +2,24 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using Azure.Core; +using Azure.Identity; +using Microsoft.PowerShell.Commands; +using Microsoft.PowerShell.PSResourceGet.Cmdlets; using NuGet.Versioning; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; -using System.Runtime.InteropServices; -using Microsoft.PowerShell.Commands; -using Microsoft.PowerShell.PSResourceGet.Cmdlets; using System.Net.Http; -using System.Globalization; +using System.Runtime.InteropServices; using System.Security; -using Azure.Core; -using Azure.Identity; namespace Microsoft.PowerShell.PSResourceGet.UtilClasses { From 30bdf6a14f723b4faeb740f89a2631b55dd5a1c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:18:40 +0200 Subject: [PATCH 14/60] Made code easier to navigate in VSCode --- src/code/InstallPSResource.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/code/InstallPSResource.cs b/src/code/InstallPSResource.cs index 67917ca78..6035c6b8b 100644 --- a/src/code/InstallPSResource.cs +++ b/src/code/InstallPSResource.cs @@ -256,7 +256,7 @@ private enum ResourceFileType #endregion - #region Method Overrides + #region Method override - Begin protected override void BeginProcessing() { @@ -274,6 +274,9 @@ protected override void BeginProcessing() _installHelper = new InstallHelper(cmdletPassedIn: this, networkCredential: networkCred); } + #endregion + + #region Method Override - Process protected override void ProcessRecord() { switch (ParameterSetName) @@ -357,7 +360,7 @@ protected override void ProcessRecord() catch (Exception) { ThrowTerminatingError(new ErrorRecord( - new ArgumentException($"Argument for parameter -RequiredResourceFile is not in proper json or hashtable format. Make sure argument is either a valid .json or .psd1 file."), + new ArgumentException($"Argument for parameter -RequiredResourceFile is not in proper json or hashtable format. Make sure argument is either a valid .json or .psd1 file."), "RequiredResourceFileNotInProperJsonFormat", ErrorCategory.InvalidData, this)); From 35836043e6559d47bdcbccb4ec5b85066a80e943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:19:10 +0200 Subject: [PATCH 15/60] Added ability to set the override env variable --- .../SetPSResourceGetInstallPathOverride.cs | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 5d068e7b3..a3b45ad56 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -33,15 +33,15 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet #endregion - #region Methods + #region Method override - Begin protected override void BeginProcessing() { // Only run on Windows for now, due to env variables on Unix being very different - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ThrowTerminatingError( new ErrorRecord( - new PSInvalidOperationException($"Error this only works on Windows for now'"), + new PSInvalidOperationException($"Error this only works on Windows for now"), "PathMissingExpectedSubdirectories", ErrorCategory.InvalidOperation, this @@ -74,8 +74,28 @@ protected override void BeginProcessing() } } + #endregion + + #region Method override - Process + protected override void ProcessRecord() { + // Assets + EnvironmentVariableTarget envScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; + + // Set env variable for install path override + Environment.SetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + Path, + envScope + ); + + // Add install path override to PSModule path + string PSModulePath = Environment.GetEnvironmentVariable( + "PSModulePath", + envScope + ); + WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); } #endregion From 69863bb866188bfaf62e5d2dc791925de3cedffe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:45:41 +0200 Subject: [PATCH 16/60] Finished barebone functionality --- .../SetPSResourceGetInstallPathOverride.cs | 62 ++++++++++++++++++- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index a3b45ad56..7b1e6235d 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -3,6 +3,7 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; +using System.Collections.Specialized; using System.Management.Automation; using System.Runtime.InteropServices; @@ -42,7 +43,7 @@ protected override void BeginProcessing() ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error this only works on Windows for now"), - "PathMissingExpectedSubdirectories", + "OsIsNotWindows", ErrorCategory.InvalidOperation, this ) @@ -54,7 +55,7 @@ protected override void BeginProcessing() ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), - "PathMissingExpectedSubdirectories", + "InputPathIsEmpty", ErrorCategory.InvalidArgument, this ) @@ -66,7 +67,23 @@ protected override void BeginProcessing() ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), - "PathMissingExpectedSubdirectories", + "InputPathIsNotRooted", + ErrorCategory.InvalidArgument, + this + ) + ); + } + + // Validate path can be expanded + try { + Environment.ExpandEnvironmentVariables(Path); + } + catch (Exception) + { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error input path could not be expanded: '{Path}'"), + "InputPathCannotBeExpanded", ErrorCategory.InvalidArgument, this ) @@ -95,7 +112,46 @@ protected override void ProcessRecord() "PSModulePath", envScope ); + if (String.IsNullOrEmpty(PSModulePath)) { + WriteVerbose(String.Format("PSModulePath in {0} context is empty.", envScope.ToString())); + System.Environment.SetEnvironmentVariable( + "PSModulePath", + Path, + envScope + ); + } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); + StringCollection PSModulePaths = new StringCollection(); + foreach (string Item in PSModulePath.Trim(';').Split(';')) { + try { + PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); + } + catch { + WriteVerbose(string.Format("Will not validate '{0}' as it could not be expanded.", Item)); + } + } + if (PSModulePaths.Contains(System.Environment.ExpandEnvironmentVariables(Path))) { + WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", envScope.ToString())); + } + else { + WriteVerbose( + String.Format( + "Override install path is not already in PSModulePath for scope '{0}'", + envScope.ToString() + ) + ); + System.Environment.SetEnvironmentVariable( + "PSModulePath", + String.Format("{0};{1}", Path, PSModulePath), + envScope + ); + WriteVerbose( + String.Format( + "Override install path was successfully added to PSModulePath for scope '{0}'.", + envScope.ToString() + ) + ); + } } #endregion From 2d1ed6fd0fc6152da0637dca9da3d562403e94c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:46:38 +0200 Subject: [PATCH 17/60] Simplified expression, thanks C# extension --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 7b1e6235d..ad6893fcc 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -121,7 +121,7 @@ protected override void ProcessRecord() ); } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); - StringCollection PSModulePaths = new StringCollection(); + StringCollection PSModulePaths = new(); foreach (string Item in PSModulePath.Trim(';').Split(';')) { try { PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); From f451010341493ed960da9481ef1dfd4d232e0d3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:32:50 +0200 Subject: [PATCH 18/60] Treat -Path more like in Save-PSResource --- .../SetPSResourceGetInstallPathOverride.cs | 137 ++++++++++-------- 1 file changed, 79 insertions(+), 58 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index ad6893fcc..312ee28d8 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -4,6 +4,8 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; using System.Collections.Specialized; +using System.IO; +using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; @@ -12,7 +14,7 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets /// /// The Set-PSResourceGetInstallPathOverride cmdlet is used to override install path for PS resources. /// - [Cmdlet(VerbsCommon.Set,"PSResourceGetInstallPathOverride",SupportsShouldProcess = true)] + [Cmdlet(VerbsCommon.Set, "PSResourceGetInstallPathOverride", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [Alias("Update-PSResourceGetInstallPathOverride")] [OutputType(typeof(void))] @@ -23,8 +25,28 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet /// /// Specifies the desired path for the override. /// - [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] - public string Path { get; set; } + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true, HelpMessage = "Path for the override.")] + [ValidateNotNullOrEmpty] + public string Path + { + get + { return _path; } + + set + { + if (WildcardPattern.ContainsWildcardCharacters(value)) + { + throw new PSArgumentException("Wildcard characters are not allowed in the path."); + } + + // This will throw if path cannot be resolved + _path = GetResolvedProviderPathFromPSPath( + Environment.ExpandEnvironmentVariables(value), + out ProviderInfo provider + ).First(); + } + } + private string _path; /// /// Specifies the scope of installation. @@ -49,46 +71,6 @@ protected override void BeginProcessing() ) ); } - - // Validate path is not null or empty - if (string.IsNullOrEmpty(Path)) { - ThrowTerminatingError( - new ErrorRecord( - new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), - "InputPathIsEmpty", - ErrorCategory.InvalidArgument, - this - ) - ); - } - - // Validate path is absolute - if (!System.IO.Path.IsPathRooted(Path)) { - ThrowTerminatingError( - new ErrorRecord( - new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), - "InputPathIsNotRooted", - ErrorCategory.InvalidArgument, - this - ) - ); - } - - // Validate path can be expanded - try { - Environment.ExpandEnvironmentVariables(Path); - } - catch (Exception) - { - ThrowTerminatingError( - new ErrorRecord( - new PSInvalidOperationException($"Error input path could not be expanded: '{Path}'"), - "InputPathCannotBeExpanded", - ErrorCategory.InvalidArgument, - this - ) - ); - } } #endregion @@ -98,29 +80,68 @@ protected override void BeginProcessing() protected override void ProcessRecord() { // Assets - EnvironmentVariableTarget envScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; + EnvironmentVariableTarget EnvScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; // Set env variable for install path override - Environment.SetEnvironmentVariable( + string PathOverrideCurrentValue = Environment.GetEnvironmentVariable( "PSResourceGetInstallPathOverride", - Path, - envScope + EnvScope ); + if (!String.IsNullOrEmpty(PathOverrideCurrentValue)) { + WriteVerbose( + String.Format( + "Current value of PSResourceGetInstallPathOverride in scope '{0}': '{1}'", + EnvScope.ToString(), + PathOverrideCurrentValue + ) + ); + } + if ( + !String.IsNullOrEmpty(PathOverrideCurrentValue) && + String.Equals( + Environment.ExpandEnvironmentVariables(PathOverrideCurrentValue), + _path, + StringComparison.Ordinal + ) + ) + { + WriteVerbose( + String.Format( + "PSResourceGetInstallPathOverride in scope '{0}' is already '{1}', no change needed.", + EnvScope.ToString(), + _path + ) + ); + } + else { + Environment.SetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + _path, + EnvScope + ); + WriteVerbose( + String.Format( + "PSResourceGetInstallPathOverride in scope '{0}' was successfully set to: '{1}'", + EnvScope.ToString(), + _path + ) + ); + } // Add install path override to PSModule path string PSModulePath = Environment.GetEnvironmentVariable( "PSModulePath", - envScope + EnvScope ); if (String.IsNullOrEmpty(PSModulePath)) { - WriteVerbose(String.Format("PSModulePath in {0} context is empty.", envScope.ToString())); + WriteVerbose(String.Format("PSModulePath in {0} context is empty.", EnvScope.ToString())); System.Environment.SetEnvironmentVariable( "PSModulePath", - Path, - envScope + _path, + EnvScope ); } - WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); + WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); StringCollection PSModulePaths = new(); foreach (string Item in PSModulePath.Trim(';').Split(';')) { try { @@ -130,25 +151,25 @@ protected override void ProcessRecord() WriteVerbose(string.Format("Will not validate '{0}' as it could not be expanded.", Item)); } } - if (PSModulePaths.Contains(System.Environment.ExpandEnvironmentVariables(Path))) { - WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", envScope.ToString())); + if (PSModulePaths.Contains(_path)) { + WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", EnvScope.ToString())); } else { WriteVerbose( String.Format( "Override install path is not already in PSModulePath for scope '{0}'", - envScope.ToString() + EnvScope.ToString() ) ); System.Environment.SetEnvironmentVariable( "PSModulePath", - String.Format("{0};{1}", Path, PSModulePath), - envScope + String.Format("{0};{1}", _path, PSModulePath), + EnvScope ); WriteVerbose( String.Format( "Override install path was successfully added to PSModulePath for scope '{0}'.", - envScope.ToString() + EnvScope.ToString() ) ); } From 90ccdc91bdf9d293c8e1d26cec0bc2f37c7cf759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:34:15 +0200 Subject: [PATCH 19/60] Looks better this way IMO --- src/code/SetPSResourceGetInstallPathOverride.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 312ee28d8..5a5b7f9f0 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -30,7 +30,9 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet public string Path { get - { return _path; } + { + return _path; + } set { From 16339a15d83a6784046f42827caa2d37631b2d83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:35:32 +0200 Subject: [PATCH 20/60] Comment update --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 5a5b7f9f0..798f0583b 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -130,7 +130,7 @@ protected override void ProcessRecord() ); } - // Add install path override to PSModule path + // Add install path override to PSModulePath string PSModulePath = Environment.GetEnvironmentVariable( "PSModulePath", EnvScope From 398b2a631fe74c7f4065e507bc786c9278b2eb0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:37:17 +0200 Subject: [PATCH 21/60] Don't think ExpandEnvironmentVariables throws if some %VAR% does not expand --- src/code/SetPSResourceGetInstallPathOverride.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 798f0583b..28fd0e06a 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -146,12 +146,7 @@ protected override void ProcessRecord() WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); StringCollection PSModulePaths = new(); foreach (string Item in PSModulePath.Trim(';').Split(';')) { - try { - PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); - } - catch { - WriteVerbose(string.Format("Will not validate '{0}' as it could not be expanded.", Item)); - } + PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); } if (PSModulePaths.Contains(_path)) { WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", EnvScope.ToString())); From ec79901912c5996f4b6674be5635366010bd843e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:45:28 +0200 Subject: [PATCH 22/60] Added -WhatIf support --- .../SetPSResourceGetInstallPathOverride.cs | 65 +++++++++++-------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 28fd0e06a..6fce9b015 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -116,18 +116,21 @@ protected override void ProcessRecord() ); } else { - Environment.SetEnvironmentVariable( - "PSResourceGetInstallPathOverride", - _path, - EnvScope - ); - WriteVerbose( - String.Format( - "PSResourceGetInstallPathOverride in scope '{0}' was successfully set to: '{1}'", - EnvScope.ToString(), - _path - ) - ); + if (this.ShouldProcess($"Set environment variable PSResourceGetPathOverride in scope '{EnvScope} to '{_path}")) + { + Environment.SetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + _path, + EnvScope + ); + WriteVerbose( + String.Format( + "PSResourceGetInstallPathOverride in scope '{0}' was successfully set to: '{1}'", + EnvScope.ToString(), + _path + ) + ); + } } // Add install path override to PSModulePath @@ -137,11 +140,14 @@ protected override void ProcessRecord() ); if (String.IsNullOrEmpty(PSModulePath)) { WriteVerbose(String.Format("PSModulePath in {0} context is empty.", EnvScope.ToString())); - System.Environment.SetEnvironmentVariable( - "PSModulePath", - _path, - EnvScope - ); + if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{_path}")) + { + System.Environment.SetEnvironmentVariable( + "PSModulePath", + _path, + EnvScope + ); + } } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); StringCollection PSModulePaths = new(); @@ -158,17 +164,20 @@ protected override void ProcessRecord() EnvScope.ToString() ) ); - System.Environment.SetEnvironmentVariable( - "PSModulePath", - String.Format("{0};{1}", _path, PSModulePath), - EnvScope - ); - WriteVerbose( - String.Format( - "Override install path was successfully added to PSModulePath for scope '{0}'.", - EnvScope.ToString() - ) - ); + if (this.ShouldProcess($"Add '{_path}' to environment pariable 'PSModulePath' in scope '{EnvScope}")) + { + System.Environment.SetEnvironmentVariable( + "PSModulePath", + String.Format("{0};{1}", _path, PSModulePath), + EnvScope + ); + WriteVerbose( + String.Format( + "Override install path was successfully added to PSModulePath for scope '{0}'.", + EnvScope.ToString() + ) + ); + } } } From c80a398edb660b45c49c02592cb67a7474a735e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:48:18 +0200 Subject: [PATCH 23/60] Remove unneccessary "using" --- src/code/SetPSResourceGetInstallPathOverride.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 6fce9b015..f850564f7 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -4,7 +4,6 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; using System.Collections.Specialized; -using System.IO; using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; From ba7b5f4d5663b07ce04d433925b72964b5af1789 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:02:41 +0200 Subject: [PATCH 24/60] Fixed adding scripts dir to PATH --- .../SetPSResourceGetInstallPathOverride.cs | 84 +++++++++++++++---- 1 file changed, 68 insertions(+), 16 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index f850564f7..68df3881f 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -82,6 +82,8 @@ protected override void ProcessRecord() { // Assets EnvironmentVariableTarget EnvScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; + string PathForModules = System.IO.Path.Combine(_path,"Modules"); + string PathForScripts = System.IO.Path.Combine(_path,"Scripts"); // Set env variable for install path override string PathOverrideCurrentValue = Environment.GetEnvironmentVariable( @@ -132,47 +134,97 @@ protected override void ProcessRecord() } } - // Add install path override to PSModulePath - string PSModulePath = Environment.GetEnvironmentVariable( + // Add install path override for modules to PSModulePath + string CurrentPSModulePath = Environment.GetEnvironmentVariable( "PSModulePath", EnvScope ); - if (String.IsNullOrEmpty(PSModulePath)) { - WriteVerbose(String.Format("PSModulePath in {0} context is empty.", EnvScope.ToString())); - if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{_path}")) + if (String.IsNullOrEmpty(CurrentPSModulePath)) { + WriteVerbose(String.Format("PSModulePath in scope '{0}' is empty.", EnvScope.ToString())); + if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{PathForModules}")) { System.Environment.SetEnvironmentVariable( "PSModulePath", - _path, + PathForModules, + EnvScope + ); + } + } + WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + StringCollection CurrentPSModulePaths = new(); + foreach (string Item in CurrentPSModulePath.Trim(';').Split(';')) { + CurrentPSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); + } + if (CurrentPSModulePaths.Contains(PathForModules)) { + WriteVerbose(String.Format("PSModulePath in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForModules)); + } + else { + WriteVerbose( + String.Format( + "PSModulePath in scope '{0}' does not already contain '{1}'", + EnvScope.ToString(), + PathForModules + ) + ); + if (this.ShouldProcess($"Add '{PathForModules}' to environment variable 'PSModulePath' in scope '{EnvScope}")) + { + System.Environment.SetEnvironmentVariable( + "PSModulePath", + String.Format("{0};{1}", PathForModules, CurrentPSModulePath), + EnvScope + ); + WriteVerbose( + String.Format( + "Successfully added '{0}' to PSModulePath in scope '{1}'", + PathForModules, + EnvScope.ToString() + ) + ); + } + } + + // Add install path override for scripts to PATH + string CurrentPATH = Environment.GetEnvironmentVariable( + "PATH", + EnvScope + ); + if (String.IsNullOrEmpty(CurrentPATH)) { + WriteVerbose(String.Format("PATH in scope '{0}' is empty.", EnvScope.ToString())); + if (this.ShouldProcess($"Set environment pariable 'PATH' in scope '{EnvScope} to '{PathForScripts}")) + { + System.Environment.SetEnvironmentVariable( + "PATH", + PathForScripts, EnvScope ); } } - WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); - StringCollection PSModulePaths = new(); - foreach (string Item in PSModulePath.Trim(';').Split(';')) { - PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); + WriteVerbose(string.Format("Current value of PATH in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + StringCollection CurrentPATHs = new(); + foreach (string Item in CurrentPATH.Trim(';').Split(';')) { + CurrentPATHs.Add(System.Environment.ExpandEnvironmentVariables(Item)); } - if (PSModulePaths.Contains(_path)) { - WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", EnvScope.ToString())); + if (CurrentPATHs.Contains(PathForScripts)) { + WriteVerbose(String.Format("PATH in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); } else { WriteVerbose( String.Format( - "Override install path is not already in PSModulePath for scope '{0}'", + "Override install path is not already in Path for scope '{0}'", EnvScope.ToString() ) ); - if (this.ShouldProcess($"Add '{_path}' to environment pariable 'PSModulePath' in scope '{EnvScope}")) + if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'PATH' in scope '{EnvScope}")) { System.Environment.SetEnvironmentVariable( "PSModulePath", - String.Format("{0};{1}", _path, PSModulePath), + String.Format("{0};{1}", PathForScripts, CurrentPATH), EnvScope ); WriteVerbose( String.Format( - "Override install path was successfully added to PSModulePath for scope '{0}'.", + "Successfully added '{0}' to PATH in scope '{1}'", + PathForScripts, EnvScope.ToString() ) ); From ce7d0f7ca34a7247bb2f4cb47e78173472b3db9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:07:07 +0200 Subject: [PATCH 25/60] PATH is named Path --- .../SetPSResourceGetInstallPathOverride.cs | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 68df3881f..0ed68ccaa 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -183,29 +183,29 @@ protected override void ProcessRecord() } } - // Add install path override for scripts to PATH - string CurrentPATH = Environment.GetEnvironmentVariable( - "PATH", + // Add install path override for scripts to Path + string CurrentPath = Environment.GetEnvironmentVariable( + "Path", EnvScope ); - if (String.IsNullOrEmpty(CurrentPATH)) { - WriteVerbose(String.Format("PATH in scope '{0}' is empty.", EnvScope.ToString())); - if (this.ShouldProcess($"Set environment pariable 'PATH' in scope '{EnvScope} to '{PathForScripts}")) + if (String.IsNullOrEmpty(CurrentPath)) { + WriteVerbose(String.Format("Path in scope '{0}' is empty.", EnvScope.ToString())); + if (this.ShouldProcess($"Set environment pariable 'Path' in scope '{EnvScope} to '{PathForScripts}")) { System.Environment.SetEnvironmentVariable( - "PATH", + "Path", PathForScripts, EnvScope ); } } - WriteVerbose(string.Format("Current value of PATH in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); - StringCollection CurrentPATHs = new(); - foreach (string Item in CurrentPATH.Trim(';').Split(';')) { - CurrentPATHs.Add(System.Environment.ExpandEnvironmentVariables(Item)); + WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + StringCollection CurrentPaths = new(); + foreach (string Item in CurrentPath.Trim(';').Split(';')) { + CurrentPaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); } - if (CurrentPATHs.Contains(PathForScripts)) { - WriteVerbose(String.Format("PATH in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); + if (CurrentPaths.Contains(PathForScripts)) { + WriteVerbose(String.Format("Path in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); } else { WriteVerbose( @@ -214,16 +214,16 @@ protected override void ProcessRecord() EnvScope.ToString() ) ); - if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'PATH' in scope '{EnvScope}")) + if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'Path' in scope '{EnvScope}")) { System.Environment.SetEnvironmentVariable( "PSModulePath", - String.Format("{0};{1}", PathForScripts, CurrentPATH), + String.Format("{0};{1}", PathForScripts, CurrentPath), EnvScope ); WriteVerbose( String.Format( - "Successfully added '{0}' to PATH in scope '{1}'", + "Successfully added '{0}' to Path in scope '{1}'", PathForScripts, EnvScope.ToString() ) From 69c88ad08a988b0db080cc0826c19de7364636b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:09:32 +0200 Subject: [PATCH 26/60] Big oops, set Path not PSModulePath for scripts dir --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 0ed68ccaa..1de8efaf4 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -217,7 +217,7 @@ protected override void ProcessRecord() if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'Path' in scope '{EnvScope}")) { System.Environment.SetEnvironmentVariable( - "PSModulePath", + "Path", String.Format("{0};{1}", PathForScripts, CurrentPath), EnvScope ); From 8026053344849315b79c5ba604e4b5e2e7eb163c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:12:20 +0200 Subject: [PATCH 27/60] Fixed verbose message --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 1de8efaf4..4b2f5d5d9 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -199,7 +199,7 @@ protected override void ProcessRecord() ); } } - WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPath)); StringCollection CurrentPaths = new(); foreach (string Item in CurrentPath.Trim(';').Split(';')) { CurrentPaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); From 853fb562aa9b48be29fb1cd680ab9178403268ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:56:10 +0200 Subject: [PATCH 28/60] Simplify some more --- .../SetPSResourceGetInstallPathOverride.cs | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 4b2f5d5d9..09e8706db 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -3,7 +3,6 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; -using System.Collections.Specialized; using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; @@ -143,7 +142,7 @@ protected override void ProcessRecord() WriteVerbose(String.Format("PSModulePath in scope '{0}' is empty.", EnvScope.ToString())); if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{PathForModules}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "PSModulePath", PathForModules, EnvScope @@ -151,10 +150,7 @@ protected override void ProcessRecord() } } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); - StringCollection CurrentPSModulePaths = new(); - foreach (string Item in CurrentPSModulePath.Trim(';').Split(';')) { - CurrentPSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); - } + string[] CurrentPSModulePaths = CurrentPSModulePath.Trim(';').Split(';').Select(s => Environment.ExpandEnvironmentVariables(s)).ToArray(); if (CurrentPSModulePaths.Contains(PathForModules)) { WriteVerbose(String.Format("PSModulePath in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForModules)); } @@ -168,7 +164,7 @@ protected override void ProcessRecord() ); if (this.ShouldProcess($"Add '{PathForModules}' to environment variable 'PSModulePath' in scope '{EnvScope}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "PSModulePath", String.Format("{0};{1}", PathForModules, CurrentPSModulePath), EnvScope @@ -192,7 +188,7 @@ protected override void ProcessRecord() WriteVerbose(String.Format("Path in scope '{0}' is empty.", EnvScope.ToString())); if (this.ShouldProcess($"Set environment pariable 'Path' in scope '{EnvScope} to '{PathForScripts}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "Path", PathForScripts, EnvScope @@ -200,10 +196,7 @@ protected override void ProcessRecord() } } WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPath)); - StringCollection CurrentPaths = new(); - foreach (string Item in CurrentPath.Trim(';').Split(';')) { - CurrentPaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); - } + string[] CurrentPaths = CurrentPath.Trim(';').Split(';').Select(s => Environment.ExpandEnvironmentVariables(s)).ToArray(); if (CurrentPaths.Contains(PathForScripts)) { WriteVerbose(String.Format("Path in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); } @@ -216,7 +209,7 @@ protected override void ProcessRecord() ); if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'Path' in scope '{EnvScope}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "Path", String.Format("{0};{1}", PathForScripts, CurrentPath), EnvScope From e5d145dea006c5452abc8b90f7190863d78cd7a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:39:31 +0200 Subject: [PATCH 29/60] Return path override if present --- src/code/Utils.cs | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index e2dc8406c..a8949b8ff 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -995,24 +995,35 @@ public static List GetPathsFromEnvVarAndScope( PSCmdlet psCmdlet, ScopeType? scope) { - GetStandardPlatformPaths( - psCmdlet, - out string myDocumentsPath, - out string programFilesPath); - - List resourcePaths = new List(); - if (scope is null || scope.Value is ScopeType.CurrentUser) - { - resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); - resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); - } - - if (scope.Value is ScopeType.AllUsers) - { - resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); - resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); + // Assets + List resourcePaths = new(); + string pathOverride = Environment.GetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User + ); + // Return override if present, else default paths + if (!string.IsNullOrEmpty(pathOverride) && Directory.Exists(pathOverride)) + { + resourcePaths.Add(Path.Combine(pathOverride, "Modules")); + resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); + } + else { + GetStandardPlatformPaths( + psCmdlet, + out string myDocumentsPath, + out string programFilesPath + ); + if (scope.Value is ScopeType.AllUsers) + { + resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); + resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); + } + else + { + resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); + resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); + } } - return resourcePaths; } From fb1d3068462897b2b47821e391697d2f87a3bf23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:48:22 +0200 Subject: [PATCH 30/60] Make more robust --- src/code/Utils.cs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index a8949b8ff..13015cecc 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -997,11 +997,30 @@ public static List GetPathsFromEnvVarAndScope( { // Assets List resourcePaths = new(); - string pathOverride = Environment.GetEnvironmentVariable( - "PSResourceGetInstallPathOverride", - (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User - ); - // Return override if present, else default paths + string pathOverride = string.Empty; + // To to get path override + try + { + pathOverride = Environment.GetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User + ); + } + catch { + psCmdlet.WriteVerbose("Path override was not found."); + } + // Try to resolve path override + if (!string.IsNullOrEmpty(pathOverride)) { + try + { + pathOverride = Path.GetFullPath(pathOverride); + } + catch + { + psCmdlet.WriteVerbose("Path override was found, but could not be resolved to full path."); + } + } + // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Directory.Exists(pathOverride)) { resourcePaths.Add(Path.Combine(pathOverride, "Modules")); From 7289deeff1d4ea9c7a6222e3c0bcf0a6b7c0305a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:50:18 +0200 Subject: [PATCH 31/60] Get empty/non-existent env variable is not expected to throw --- src/code/Utils.cs | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 13015cecc..edef7c496 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -997,18 +997,11 @@ public static List GetPathsFromEnvVarAndScope( { // Assets List resourcePaths = new(); - string pathOverride = string.Empty; - // To to get path override - try - { - pathOverride = Environment.GetEnvironmentVariable( - "PSResourceGetInstallPathOverride", - (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User - ); - } - catch { - psCmdlet.WriteVerbose("Path override was not found."); - } + // Get value of path override environment variable + string pathOverride = Environment.GetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User + ); // Try to resolve path override if (!string.IsNullOrEmpty(pathOverride)) { try From 76d75e2df4cf8242ffb8a067b18464c96254e4ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 13:52:34 +0200 Subject: [PATCH 32/60] More robust --- src/code/Utils.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index edef7c496..066768d68 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -1008,8 +1008,9 @@ public static List GetPathsFromEnvVarAndScope( { pathOverride = Path.GetFullPath(pathOverride); } - catch + catch (ArgumentException) { + pathOverride = string.Empty; psCmdlet.WriteVerbose("Path override was found, but could not be resolved to full path."); } } From 288edeca3bda3c8148a2d42117b9657a7fd900b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 14:04:00 +0200 Subject: [PATCH 33/60] Expand, not resolve --- src/code/Utils.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 066768d68..8f1feb354 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -1002,20 +1002,20 @@ public static List GetPathsFromEnvVarAndScope( "PSResourceGetInstallPathOverride", (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User ); - // Try to resolve path override + // Try to expand path override if (!string.IsNullOrEmpty(pathOverride)) { try { - pathOverride = Path.GetFullPath(pathOverride); + pathOverride = Environment.ExpandEnvironmentVariables(pathOverride); } catch (ArgumentException) { pathOverride = string.Empty; - psCmdlet.WriteVerbose("Path override was found, but could not be resolved to full path."); + psCmdlet.WriteVerbose("Path override was found, but could not expand environment variable(s)."); } } // Return override if present, else use default paths - if (!string.IsNullOrEmpty(pathOverride) && Directory.Exists(pathOverride)) + if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { resourcePaths.Add(Path.Combine(pathOverride, "Modules")); resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); From 89f3dfce8a4548e19d540058874cd605114fc2a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 14:12:57 +0200 Subject: [PATCH 34/60] Add verbose message --- src/code/Utils.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 8f1feb354..78aa605a7 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -1017,6 +1017,7 @@ public static List GetPathsFromEnvVarAndScope( // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { + psCmdlet.WriteVerbose(string.Format("Path override was found, using '{0}' as base.",pathOverride)); resourcePaths.Add(Path.Combine(pathOverride, "Modules")); resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); } From 9b4b60f1db9ab4ba091d3db2cc38f8b1fb79fee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 17:12:47 +0200 Subject: [PATCH 35/60] Don't get paths twice --- src/code/InstallPSResource.cs | 38 +++++++++++++++++------------------ 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/code/InstallPSResource.cs b/src/code/InstallPSResource.cs index a65797268..67917ca78 100644 --- a/src/code/InstallPSResource.cs +++ b/src/code/InstallPSResource.cs @@ -17,15 +17,15 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets /// The Install-PSResource cmdlet installs a resource. /// It returns nothing. /// - [Cmdlet(VerbsLifecycle.Install, - "PSResource", - DefaultParameterSetName = "NameParameterSet", + [Cmdlet(VerbsLifecycle.Install, + "PSResource", + DefaultParameterSetName = "NameParameterSet", SupportsShouldProcess = true)] [Alias("isres")] public sealed class InstallPSResource : PSCmdlet { - #region Parameters + #region Parameters /// /// Specifies the exact names of resources to install from a repository. @@ -42,7 +42,7 @@ class InstallPSResource : PSCmdlet [Parameter(ParameterSetName = NameParameterSet, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string Version { get; set; } - + /// /// Specifies to allow installation of prerelease versions /// @@ -83,9 +83,9 @@ public string TemporaryPath set { - if (WildcardPattern.ContainsWildcardCharacters(value)) - { - throw new PSArgumentException("Wildcard characters are not allowed in the temporary path."); + if (WildcardPattern.ContainsWildcardCharacters(value)) + { + throw new PSArgumentException("Wildcard characters are not allowed in the temporary path."); } // This will throw if path cannot be resolved @@ -99,7 +99,7 @@ public string TemporaryPath /// [Parameter] public SwitchParameter TrustRepository { get; set; } - + /// /// Overwrites a previously installed resource with the same name and version. /// @@ -130,7 +130,7 @@ public string TemporaryPath /// [Parameter] public SwitchParameter SkipDependencyCheck { get; set; } - + /// /// Check validation for signed and catalog files /// @@ -265,7 +265,7 @@ protected override void BeginProcessing() RepositorySettings.CheckRepositoryStore(); _pathsToInstallPkg = Utils.GetAllInstallationPaths(this, Scope); - List pathsToSearch = Utils.GetAllResourcePaths(this, Scope); + List pathsToSearch = _pathsToInstallPkg; // Only need to find packages installed if -Reinstall is not passed in _packagesOnMachine = Reinstall ? new HashSet(StringComparer.CurrentCultureIgnoreCase) : Utils.GetInstalledPackages(pathsToSearch, this); @@ -287,7 +287,7 @@ protected override void ProcessRecord() pkgCredential: Credential, reqResourceParams: null); break; - + case InputObjectParameterSet: foreach (var inputObj in InputObject) { string normalizedVersionString = Utils.GetNormalizedVersionString(inputObj.Version.ToString(), inputObj.Prerelease); @@ -362,7 +362,7 @@ protected override void ProcessRecord() ErrorCategory.InvalidData, this)); } - + RequiredResourceHelper(pkgsInFile); break; @@ -379,7 +379,7 @@ protected override void ProcessRecord() } } */ - + Hashtable pkgsHash = null; try { @@ -441,7 +441,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) { var pkgNameEmptyOrWhitespaceError = new ErrorRecord( new ArgumentException($"The package name '{pkgName}' provided cannot be an empty string or whitespace."), - "pkgNameEmptyOrWhitespaceError", + "pkgNameEmptyOrWhitespaceError", ErrorCategory.InvalidArgument, this); @@ -454,7 +454,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) { var requiredResourceHashtableInputFormatError = new ErrorRecord( new ArgumentException($"The RequiredResource input with name '{pkgName}' does not have a valid value, the value must be a hashtable."), - "RequiredResourceHashtableInputFormatError", + "RequiredResourceHashtableInputFormatError", ErrorCategory.InvalidArgument, this); @@ -483,7 +483,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) ThrowTerminatingError(ParameterParsingError); } } - + if (pkgParams.Scope == ScopeType.AllUsers) { _pathsToInstallPkg = Utils.GetAllInstallationPaths(this, pkgParams.Scope); @@ -513,10 +513,10 @@ private void ProcessInstallHelper(string[] pkgNames, string pkgVersion, bool pkg "NameContainsWildcard", ErrorCategory.InvalidArgument, this)); - + return; } - + foreach (string error in errorMsgs) { WriteError(new ErrorRecord( From 9e8617c6063513d6d24b91a6cb44514e2775bbbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sat, 13 Jul 2024 17:13:09 +0200 Subject: [PATCH 36/60] Add newline before comments --- src/code/Utils.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 78aa605a7..0bb1e6df5 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -997,11 +997,13 @@ public static List GetPathsFromEnvVarAndScope( { // Assets List resourcePaths = new(); + // Get value of path override environment variable string pathOverride = Environment.GetEnvironmentVariable( "PSResourceGetInstallPathOverride", (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User ); + // Try to expand path override if (!string.IsNullOrEmpty(pathOverride)) { try @@ -1014,6 +1016,7 @@ public static List GetPathsFromEnvVarAndScope( psCmdlet.WriteVerbose("Path override was found, but could not expand environment variable(s)."); } } + // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { @@ -1038,6 +1041,8 @@ out string programFilesPath resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); } } + + // Return results return resourcePaths; } From 02b79b75bb918b9716cd8c568126f5a21314b00d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 11:51:47 +0200 Subject: [PATCH 37/60] Remove empty newline --- src/code/GetInstalledPSResource.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/code/GetInstalledPSResource.cs b/src/code/GetInstalledPSResource.cs index dafd36400..fc30d5eb6 100644 --- a/src/code/GetInstalledPSResource.cs +++ b/src/code/GetInstalledPSResource.cs @@ -89,7 +89,6 @@ protected override void BeginProcessing() { ThrowTerminatingError(new ErrorRecord( new PSArgumentException($"Error: Could not resolve provided Path argument '{Path}' into a single path."), - "ErrorInvalidPathArgument", ErrorCategory.InvalidArgument, this)); @@ -153,7 +152,7 @@ protected override void ProcessRecord() List pkgsNotFound = new List(); foreach (string name in namesToSearch) { - if (!pkgsFound.Contains(name, StringComparer.OrdinalIgnoreCase)) + if (!pkgsFound.Contains(name, StringComparer.OrdinalIgnoreCase)) { if (name.Contains('*')) { From 82e501c0380088cbb1a8097631f19c6d9338351d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 12:04:32 +0200 Subject: [PATCH 38/60] Added new cmdlet --- src/Microsoft.PowerShell.PSResourceGet.psd1 | 25 ++++--- .../SetPSResourceGetInstallPathOverride.cs | 70 +++++++++++++++++++ 2 files changed, 84 insertions(+), 11 deletions(-) create mode 100644 src/code/SetPSResourceGetInstallPathOverride.cs diff --git a/src/Microsoft.PowerShell.PSResourceGet.psd1 b/src/Microsoft.PowerShell.PSResourceGet.psd1 index b5abe9ae6..afdb7a2ac 100644 --- a/src/Microsoft.PowerShell.PSResourceGet.psd1 +++ b/src/Microsoft.PowerShell.PSResourceGet.psd1 @@ -21,29 +21,32 @@ 'Get-PSResourceRepository', 'Get-PSScriptFileInfo', 'Install-PSResource', + 'New-PSScriptFileInfo', + 'Publish-PSResource', 'Register-PSResourceRepository', 'Save-PSResource', + 'Set-PSResourceGetInstallPathOverride', 'Set-PSResourceRepository', - 'New-PSScriptFileInfo', 'Test-PSScriptFileInfo', - 'Update-PSScriptFileInfo', - 'Publish-PSResource', 'Uninstall-PSResource', 'Unregister-PSResourceRepository', 'Update-PSModuleManifest', - 'Update-PSResource' + 'Update-PSResource', + 'Update-PSScriptFileInfo' ) FunctionsToExport = @( 'Import-PSGetRepository' ) - VariablesToExport = 'PSGetPath' - AliasesToExport = @( + VariablesToExport = 'PSGetPath' + AliasesToExport = @( 'Get-PSResource', 'fdres', 'isres', 'pbres', - 'udres') - PrivateData = @{ + 'Update-PSResourceGetInstallPathOverride', + 'udres' + ) + PrivateData = @{ PSData = @{ Prerelease = 'preview1' Tags = @('PackageManagement', @@ -59,7 +62,7 @@ ### New Features -- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, +- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, #1573, #1576, #1587, #1588, #1589, #1594, #1598, #1600, #1602, #1604, #1615) ### Bug Fixes @@ -111,7 +114,7 @@ - Bug fix Artifactory v2 endpoint failures (#1428) - Bug fix Artifactory v3 endpoint failures (#1427) - Bug fix `-RequiredResource` silent failures (#1426) -- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) +- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) ## 0.9.0-rc1 @@ -193,7 +196,7 @@ - Improve error handling in Uninstall-PSResource (#1215) - Change resolved paths to use GetResolvedProviderPathFromPSPath (#1209) - Bug fix for Get-InstalledPSResource returning type of scripts as module (#1198) - + ## 0.5.22-beta22 diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs new file mode 100644 index 000000000..f416d82e0 --- /dev/null +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Microsoft.PowerShell.PSResourceGet.UtilClasses; +using System; +using System.Management.Automation; + +namespace Microsoft.PowerShell.PSResourceGet.Cmdlets +{ + /// + /// The Set-PSResourceGetInstallPathOverride cmdlet is used to override install path for PS resources. + /// + [Cmdlet(VerbsCommon.Set,"PSResourceGetInstallPathOverride",SupportsShouldProcess = true)] + [Alias("Update-PSResourceGetInstallPathOverride")] + [OutputType(typeof(void))] + + public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet + { + #region Parameters + + /// + /// Specifies the desired path for the override. + /// + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] + public string Path { get; set; } + + /// + /// Specifies the scope of installation. + /// + [Parameter(Position = 1)] + public ScopeType Scope { get; set; } + + #endregion + + #region Methods + + protected override void BeginProcessing() + { + // Validate path is not null or empty + if (string.IsNullOrEmpty(Path)) { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), + "PathMissingExpectedSubdirectories", + ErrorCategory.InvalidOperation, + this + ) + ); + } + + // Validate path is absolute + if (!System.IO.Path.IsPathRooted(Path)) { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), + "PathMissingExpectedSubdirectories", + ErrorCategory.InvalidOperation, + this + ) + ); + } + } + + protected override void ProcessRecord() + { + } + + #endregion + } +} From 4b02c099b455c6518ee26a7493774f724044329b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 12:08:43 +0200 Subject: [PATCH 39/60] "using System;" was written twice --- src/code/ServerApiCall.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/code/ServerApiCall.cs b/src/code/ServerApiCall.cs index 9f8bf4fe9..cbe429c28 100644 --- a/src/code/ServerApiCall.cs +++ b/src/code/ServerApiCall.cs @@ -2,15 +2,14 @@ // Licensed under the MIT License. using Microsoft.PowerShell.PSResourceGet.UtilClasses; +using NuGet.Versioning; using System; using System.IO; -using System.Net.Http; -using NuGet.Versioning; +using System.Management.Automation; using System.Net; -using System.Text; +using System.Net.Http; using System.Runtime.ExceptionServices; -using System.Management.Automation; -using System; +using System.Text; namespace Microsoft.PowerShell.PSResourceGet.Cmdlets { @@ -28,11 +27,11 @@ internal abstract class ServerApiCall : IServerAPICalls public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCredential) { this.Repository = repository; - + HttpClientHandler handler = new HttpClientHandler(); bool token = false; - if(networkCredential != null) + if(networkCredential != null) { token = String.Equals("token", networkCredential.UserName) ? true : false; }; @@ -47,7 +46,7 @@ public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCrede } else { handler.Credentials = networkCredential; - + _sessionClient = new HttpClient(handler); }; _sessionClient.Timeout = TimeSpan.FromMinutes(10); From a86eae5a8ea858e09cef8ed583f9b3bf4fe35321 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 17:52:26 +0200 Subject: [PATCH 40/60] Only for Windows because env variables is very different on Unix + Make path to returning standard paths shorter --- .../SetPSResourceGetInstallPathOverride.cs | 17 +++- src/code/Utils.cs | 78 ++++++++++++------- 2 files changed, 66 insertions(+), 29 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index f416d82e0..5d068e7b3 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -4,6 +4,7 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; using System.Management.Automation; +using System.Runtime.InteropServices; namespace Microsoft.PowerShell.PSResourceGet.Cmdlets { @@ -36,13 +37,25 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet protected override void BeginProcessing() { + // Only run on Windows for now, due to env variables on Unix being very different + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error this only works on Windows for now'"), + "PathMissingExpectedSubdirectories", + ErrorCategory.InvalidOperation, + this + ) + ); + } + // Validate path is not null or empty if (string.IsNullOrEmpty(Path)) { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), "PathMissingExpectedSubdirectories", - ErrorCategory.InvalidOperation, + ErrorCategory.InvalidArgument, this ) ); @@ -54,7 +67,7 @@ protected override void BeginProcessing() new ErrorRecord( new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), "PathMissingExpectedSubdirectories", - ErrorCategory.InvalidOperation, + ErrorCategory.InvalidArgument, this ) ); diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 0bb1e6df5..ee173388a 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -990,60 +990,84 @@ public static string GetInstalledPackageName(string pkgPath) return new DirectoryInfo(pkgPath).Parent.Name; } - // Find all potential resource paths - public static List GetPathsFromEnvVarAndScope( + // Get standard install paths given scope + public static List GetStandardPathsForScope( PSCmdlet psCmdlet, ScopeType? scope) { // Assets List resourcePaths = new(); + // Get standard paths + GetStandardPlatformPaths( + psCmdlet, + out string myDocumentsPath, + out string programFilesPath + ); + + // Add paths to output + if (scope.Value is ScopeType.AllUsers) + { + resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); + resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); + } + else + { + resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); + resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); + } + + // Return results + return resourcePaths; + } + + // Find all potential resource paths + public static List GetPathsFromEnvVarAndScope( + PSCmdlet psCmdlet, + ScopeType? scope) + { + // Path override is only implemented for Windows so far + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { + return GetStandardPathsForScope(psCmdlet,scope); + } + // Get value of path override environment variable string pathOverride = Environment.GetEnvironmentVariable( "PSResourceGetInstallPathOverride", (scope.Value is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User ); - // Try to expand path override - if (!string.IsNullOrEmpty(pathOverride)) { + // Return standard paths if no override was found, else try to expand paths found in override + if (string.IsNullOrEmpty(pathOverride)) { + return GetStandardPathsForScope(psCmdlet,scope); + } + else { try { pathOverride = Environment.ExpandEnvironmentVariables(pathOverride); } catch (ArgumentException) { - pathOverride = string.Empty; - psCmdlet.WriteVerbose("Path override was found, but could not expand environment variable(s)."); + psCmdlet.WriteWarning("Path override was found, but could not expand environment variable(s). Falling back to standard paths."); + return GetStandardPathsForScope(psCmdlet,scope); } } // Return override if present, else use default paths if (!string.IsNullOrEmpty(pathOverride) && Path.IsPathRooted(pathOverride) && Directory.Exists(pathOverride)) { - psCmdlet.WriteVerbose(string.Format("Path override was found, using '{0}' as base.",pathOverride)); - resourcePaths.Add(Path.Combine(pathOverride, "Modules")); - resourcePaths.Add(Path.Combine(pathOverride, "Scripts")); + psCmdlet.WriteVerbose(string.Format("Path override was found, using '{0}' as base.", pathOverride)); + // Assets + List resourcePaths = new() + { + Path.Combine(pathOverride, "Modules"), + Path.Combine(pathOverride, "Scripts") + }; + return resourcePaths; } else { - GetStandardPlatformPaths( - psCmdlet, - out string myDocumentsPath, - out string programFilesPath - ); - if (scope.Value is ScopeType.AllUsers) - { - resourcePaths.Add(Path.Combine(programFilesPath, "Modules")); - resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); - } - else - { - resourcePaths.Add(Path.Combine(myDocumentsPath, "Modules")); - resourcePaths.Add(Path.Combine(myDocumentsPath, "Scripts")); - } + return GetStandardPathsForScope(psCmdlet,scope); } - - // Return results - return resourcePaths; } public static List GetAllResourcePaths( From abb819ea2530a36cb104bd1da5dc5dce7731537b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 17:53:33 +0200 Subject: [PATCH 41/60] Sort using alphabetically --- src/code/Utils.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index ee173388a..8c3a07c6f 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -2,24 +2,24 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using Azure.Core; +using Azure.Identity; +using Microsoft.PowerShell.Commands; +using Microsoft.PowerShell.PSResourceGet.Cmdlets; using NuGet.Versioning; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; -using System.Runtime.InteropServices; -using Microsoft.PowerShell.Commands; -using Microsoft.PowerShell.PSResourceGet.Cmdlets; using System.Net.Http; -using System.Globalization; +using System.Runtime.InteropServices; using System.Security; -using Azure.Core; -using Azure.Identity; namespace Microsoft.PowerShell.PSResourceGet.UtilClasses { From 8ad86c536f1d0b68f58fce531198cfc17961fc2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:18:40 +0200 Subject: [PATCH 42/60] Made code easier to navigate in VSCode --- src/code/InstallPSResource.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/code/InstallPSResource.cs b/src/code/InstallPSResource.cs index 67917ca78..6035c6b8b 100644 --- a/src/code/InstallPSResource.cs +++ b/src/code/InstallPSResource.cs @@ -256,7 +256,7 @@ private enum ResourceFileType #endregion - #region Method Overrides + #region Method override - Begin protected override void BeginProcessing() { @@ -274,6 +274,9 @@ protected override void BeginProcessing() _installHelper = new InstallHelper(cmdletPassedIn: this, networkCredential: networkCred); } + #endregion + + #region Method Override - Process protected override void ProcessRecord() { switch (ParameterSetName) @@ -357,7 +360,7 @@ protected override void ProcessRecord() catch (Exception) { ThrowTerminatingError(new ErrorRecord( - new ArgumentException($"Argument for parameter -RequiredResourceFile is not in proper json or hashtable format. Make sure argument is either a valid .json or .psd1 file."), + new ArgumentException($"Argument for parameter -RequiredResourceFile is not in proper json or hashtable format. Make sure argument is either a valid .json or .psd1 file."), "RequiredResourceFileNotInProperJsonFormat", ErrorCategory.InvalidData, this)); From 92a72cf1027d53cfbfbdab4d50c501eb1b12a08d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:19:10 +0200 Subject: [PATCH 43/60] Added ability to set the override env variable --- .../SetPSResourceGetInstallPathOverride.cs | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 5d068e7b3..a3b45ad56 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -33,15 +33,15 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet #endregion - #region Methods + #region Method override - Begin protected override void BeginProcessing() { // Only run on Windows for now, due to env variables on Unix being very different - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ThrowTerminatingError( new ErrorRecord( - new PSInvalidOperationException($"Error this only works on Windows for now'"), + new PSInvalidOperationException($"Error this only works on Windows for now"), "PathMissingExpectedSubdirectories", ErrorCategory.InvalidOperation, this @@ -74,8 +74,28 @@ protected override void BeginProcessing() } } + #endregion + + #region Method override - Process + protected override void ProcessRecord() { + // Assets + EnvironmentVariableTarget envScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; + + // Set env variable for install path override + Environment.SetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + Path, + envScope + ); + + // Add install path override to PSModule path + string PSModulePath = Environment.GetEnvironmentVariable( + "PSModulePath", + envScope + ); + WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); } #endregion From d06798769f14a20ed29656676104ca2870d8da3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:45:41 +0200 Subject: [PATCH 44/60] Finished barebone functionality --- .../SetPSResourceGetInstallPathOverride.cs | 62 ++++++++++++++++++- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index a3b45ad56..7b1e6235d 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -3,6 +3,7 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; +using System.Collections.Specialized; using System.Management.Automation; using System.Runtime.InteropServices; @@ -42,7 +43,7 @@ protected override void BeginProcessing() ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error this only works on Windows for now"), - "PathMissingExpectedSubdirectories", + "OsIsNotWindows", ErrorCategory.InvalidOperation, this ) @@ -54,7 +55,7 @@ protected override void BeginProcessing() ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), - "PathMissingExpectedSubdirectories", + "InputPathIsEmpty", ErrorCategory.InvalidArgument, this ) @@ -66,7 +67,23 @@ protected override void BeginProcessing() ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), - "PathMissingExpectedSubdirectories", + "InputPathIsNotRooted", + ErrorCategory.InvalidArgument, + this + ) + ); + } + + // Validate path can be expanded + try { + Environment.ExpandEnvironmentVariables(Path); + } + catch (Exception) + { + ThrowTerminatingError( + new ErrorRecord( + new PSInvalidOperationException($"Error input path could not be expanded: '{Path}'"), + "InputPathCannotBeExpanded", ErrorCategory.InvalidArgument, this ) @@ -95,7 +112,46 @@ protected override void ProcessRecord() "PSModulePath", envScope ); + if (String.IsNullOrEmpty(PSModulePath)) { + WriteVerbose(String.Format("PSModulePath in {0} context is empty.", envScope.ToString())); + System.Environment.SetEnvironmentVariable( + "PSModulePath", + Path, + envScope + ); + } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); + StringCollection PSModulePaths = new StringCollection(); + foreach (string Item in PSModulePath.Trim(';').Split(';')) { + try { + PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); + } + catch { + WriteVerbose(string.Format("Will not validate '{0}' as it could not be expanded.", Item)); + } + } + if (PSModulePaths.Contains(System.Environment.ExpandEnvironmentVariables(Path))) { + WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", envScope.ToString())); + } + else { + WriteVerbose( + String.Format( + "Override install path is not already in PSModulePath for scope '{0}'", + envScope.ToString() + ) + ); + System.Environment.SetEnvironmentVariable( + "PSModulePath", + String.Format("{0};{1}", Path, PSModulePath), + envScope + ); + WriteVerbose( + String.Format( + "Override install path was successfully added to PSModulePath for scope '{0}'.", + envScope.ToString() + ) + ); + } } #endregion From 8f2cc35156372a65bdb17f9e9598e3cbfe1b2629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 18:46:38 +0200 Subject: [PATCH 45/60] Simplified expression, thanks C# extension --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 7b1e6235d..ad6893fcc 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -121,7 +121,7 @@ protected override void ProcessRecord() ); } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); - StringCollection PSModulePaths = new StringCollection(); + StringCollection PSModulePaths = new(); foreach (string Item in PSModulePath.Trim(';').Split(';')) { try { PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); From f278bb8962864b3991cfa254f542407f35d09158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:32:50 +0200 Subject: [PATCH 46/60] Treat -Path more like in Save-PSResource --- .../SetPSResourceGetInstallPathOverride.cs | 137 ++++++++++-------- 1 file changed, 79 insertions(+), 58 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index ad6893fcc..312ee28d8 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -4,6 +4,8 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; using System.Collections.Specialized; +using System.IO; +using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; @@ -12,7 +14,7 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets /// /// The Set-PSResourceGetInstallPathOverride cmdlet is used to override install path for PS resources. /// - [Cmdlet(VerbsCommon.Set,"PSResourceGetInstallPathOverride",SupportsShouldProcess = true)] + [Cmdlet(VerbsCommon.Set, "PSResourceGetInstallPathOverride", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [Alias("Update-PSResourceGetInstallPathOverride")] [OutputType(typeof(void))] @@ -23,8 +25,28 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet /// /// Specifies the desired path for the override. /// - [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] - public string Path { get; set; } + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true, HelpMessage = "Path for the override.")] + [ValidateNotNullOrEmpty] + public string Path + { + get + { return _path; } + + set + { + if (WildcardPattern.ContainsWildcardCharacters(value)) + { + throw new PSArgumentException("Wildcard characters are not allowed in the path."); + } + + // This will throw if path cannot be resolved + _path = GetResolvedProviderPathFromPSPath( + Environment.ExpandEnvironmentVariables(value), + out ProviderInfo provider + ).First(); + } + } + private string _path; /// /// Specifies the scope of installation. @@ -49,46 +71,6 @@ protected override void BeginProcessing() ) ); } - - // Validate path is not null or empty - if (string.IsNullOrEmpty(Path)) { - ThrowTerminatingError( - new ErrorRecord( - new PSInvalidOperationException($"Error input path is null or empty: '{Path}'"), - "InputPathIsEmpty", - ErrorCategory.InvalidArgument, - this - ) - ); - } - - // Validate path is absolute - if (!System.IO.Path.IsPathRooted(Path)) { - ThrowTerminatingError( - new ErrorRecord( - new PSInvalidOperationException($"Error input path is not rooted / absolute: '{Path}'"), - "InputPathIsNotRooted", - ErrorCategory.InvalidArgument, - this - ) - ); - } - - // Validate path can be expanded - try { - Environment.ExpandEnvironmentVariables(Path); - } - catch (Exception) - { - ThrowTerminatingError( - new ErrorRecord( - new PSInvalidOperationException($"Error input path could not be expanded: '{Path}'"), - "InputPathCannotBeExpanded", - ErrorCategory.InvalidArgument, - this - ) - ); - } } #endregion @@ -98,29 +80,68 @@ protected override void BeginProcessing() protected override void ProcessRecord() { // Assets - EnvironmentVariableTarget envScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; + EnvironmentVariableTarget EnvScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; // Set env variable for install path override - Environment.SetEnvironmentVariable( + string PathOverrideCurrentValue = Environment.GetEnvironmentVariable( "PSResourceGetInstallPathOverride", - Path, - envScope + EnvScope ); + if (!String.IsNullOrEmpty(PathOverrideCurrentValue)) { + WriteVerbose( + String.Format( + "Current value of PSResourceGetInstallPathOverride in scope '{0}': '{1}'", + EnvScope.ToString(), + PathOverrideCurrentValue + ) + ); + } + if ( + !String.IsNullOrEmpty(PathOverrideCurrentValue) && + String.Equals( + Environment.ExpandEnvironmentVariables(PathOverrideCurrentValue), + _path, + StringComparison.Ordinal + ) + ) + { + WriteVerbose( + String.Format( + "PSResourceGetInstallPathOverride in scope '{0}' is already '{1}', no change needed.", + EnvScope.ToString(), + _path + ) + ); + } + else { + Environment.SetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + _path, + EnvScope + ); + WriteVerbose( + String.Format( + "PSResourceGetInstallPathOverride in scope '{0}' was successfully set to: '{1}'", + EnvScope.ToString(), + _path + ) + ); + } // Add install path override to PSModule path string PSModulePath = Environment.GetEnvironmentVariable( "PSModulePath", - envScope + EnvScope ); if (String.IsNullOrEmpty(PSModulePath)) { - WriteVerbose(String.Format("PSModulePath in {0} context is empty.", envScope.ToString())); + WriteVerbose(String.Format("PSModulePath in {0} context is empty.", EnvScope.ToString())); System.Environment.SetEnvironmentVariable( "PSModulePath", - Path, - envScope + _path, + EnvScope ); } - WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", envScope.ToString(), PSModulePath)); + WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); StringCollection PSModulePaths = new(); foreach (string Item in PSModulePath.Trim(';').Split(';')) { try { @@ -130,25 +151,25 @@ protected override void ProcessRecord() WriteVerbose(string.Format("Will not validate '{0}' as it could not be expanded.", Item)); } } - if (PSModulePaths.Contains(System.Environment.ExpandEnvironmentVariables(Path))) { - WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", envScope.ToString())); + if (PSModulePaths.Contains(_path)) { + WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", EnvScope.ToString())); } else { WriteVerbose( String.Format( "Override install path is not already in PSModulePath for scope '{0}'", - envScope.ToString() + EnvScope.ToString() ) ); System.Environment.SetEnvironmentVariable( "PSModulePath", - String.Format("{0};{1}", Path, PSModulePath), - envScope + String.Format("{0};{1}", _path, PSModulePath), + EnvScope ); WriteVerbose( String.Format( "Override install path was successfully added to PSModulePath for scope '{0}'.", - envScope.ToString() + EnvScope.ToString() ) ); } From eabf85dc0701b9fecbbe365e2cadf55dd87d10d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:34:15 +0200 Subject: [PATCH 47/60] Looks better this way IMO --- src/code/SetPSResourceGetInstallPathOverride.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 312ee28d8..5a5b7f9f0 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -30,7 +30,9 @@ public sealed class SetPSResourceGetInstallPathOverride : PSCmdlet public string Path { get - { return _path; } + { + return _path; + } set { From 8b1bdce708cedcb95bac7a8705e1a5f3c47030e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:35:32 +0200 Subject: [PATCH 48/60] Comment update --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 5a5b7f9f0..798f0583b 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -130,7 +130,7 @@ protected override void ProcessRecord() ); } - // Add install path override to PSModule path + // Add install path override to PSModulePath string PSModulePath = Environment.GetEnvironmentVariable( "PSModulePath", EnvScope From fc2017558d7ab68daf36c5fc431a2660fcbaaee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:37:17 +0200 Subject: [PATCH 49/60] Don't think ExpandEnvironmentVariables throws if some %VAR% does not expand --- src/code/SetPSResourceGetInstallPathOverride.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 798f0583b..28fd0e06a 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -146,12 +146,7 @@ protected override void ProcessRecord() WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); StringCollection PSModulePaths = new(); foreach (string Item in PSModulePath.Trim(';').Split(';')) { - try { - PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); - } - catch { - WriteVerbose(string.Format("Will not validate '{0}' as it could not be expanded.", Item)); - } + PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); } if (PSModulePaths.Contains(_path)) { WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", EnvScope.ToString())); From 854e59965475dced53d9f7e8cb1d482e71de1226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:45:28 +0200 Subject: [PATCH 50/60] Added -WhatIf support --- .../SetPSResourceGetInstallPathOverride.cs | 65 +++++++++++-------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 28fd0e06a..6fce9b015 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -116,18 +116,21 @@ protected override void ProcessRecord() ); } else { - Environment.SetEnvironmentVariable( - "PSResourceGetInstallPathOverride", - _path, - EnvScope - ); - WriteVerbose( - String.Format( - "PSResourceGetInstallPathOverride in scope '{0}' was successfully set to: '{1}'", - EnvScope.ToString(), - _path - ) - ); + if (this.ShouldProcess($"Set environment variable PSResourceGetPathOverride in scope '{EnvScope} to '{_path}")) + { + Environment.SetEnvironmentVariable( + "PSResourceGetInstallPathOverride", + _path, + EnvScope + ); + WriteVerbose( + String.Format( + "PSResourceGetInstallPathOverride in scope '{0}' was successfully set to: '{1}'", + EnvScope.ToString(), + _path + ) + ); + } } // Add install path override to PSModulePath @@ -137,11 +140,14 @@ protected override void ProcessRecord() ); if (String.IsNullOrEmpty(PSModulePath)) { WriteVerbose(String.Format("PSModulePath in {0} context is empty.", EnvScope.ToString())); - System.Environment.SetEnvironmentVariable( - "PSModulePath", - _path, - EnvScope - ); + if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{_path}")) + { + System.Environment.SetEnvironmentVariable( + "PSModulePath", + _path, + EnvScope + ); + } } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); StringCollection PSModulePaths = new(); @@ -158,17 +164,20 @@ protected override void ProcessRecord() EnvScope.ToString() ) ); - System.Environment.SetEnvironmentVariable( - "PSModulePath", - String.Format("{0};{1}", _path, PSModulePath), - EnvScope - ); - WriteVerbose( - String.Format( - "Override install path was successfully added to PSModulePath for scope '{0}'.", - EnvScope.ToString() - ) - ); + if (this.ShouldProcess($"Add '{_path}' to environment pariable 'PSModulePath' in scope '{EnvScope}")) + { + System.Environment.SetEnvironmentVariable( + "PSModulePath", + String.Format("{0};{1}", _path, PSModulePath), + EnvScope + ); + WriteVerbose( + String.Format( + "Override install path was successfully added to PSModulePath for scope '{0}'.", + EnvScope.ToString() + ) + ); + } } } From 2682b9851e87df21ead81540ec7a97de2c02bc13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 19:48:18 +0200 Subject: [PATCH 51/60] Remove unneccessary "using" --- src/code/SetPSResourceGetInstallPathOverride.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 6fce9b015..f850564f7 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -4,7 +4,6 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; using System.Collections.Specialized; -using System.IO; using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; From e2e8d0bd142f0e21ff1c8aed69243218713e690e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:02:41 +0200 Subject: [PATCH 52/60] Fixed adding scripts dir to PATH --- .../SetPSResourceGetInstallPathOverride.cs | 84 +++++++++++++++---- 1 file changed, 68 insertions(+), 16 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index f850564f7..68df3881f 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -82,6 +82,8 @@ protected override void ProcessRecord() { // Assets EnvironmentVariableTarget EnvScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; + string PathForModules = System.IO.Path.Combine(_path,"Modules"); + string PathForScripts = System.IO.Path.Combine(_path,"Scripts"); // Set env variable for install path override string PathOverrideCurrentValue = Environment.GetEnvironmentVariable( @@ -132,47 +134,97 @@ protected override void ProcessRecord() } } - // Add install path override to PSModulePath - string PSModulePath = Environment.GetEnvironmentVariable( + // Add install path override for modules to PSModulePath + string CurrentPSModulePath = Environment.GetEnvironmentVariable( "PSModulePath", EnvScope ); - if (String.IsNullOrEmpty(PSModulePath)) { - WriteVerbose(String.Format("PSModulePath in {0} context is empty.", EnvScope.ToString())); - if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{_path}")) + if (String.IsNullOrEmpty(CurrentPSModulePath)) { + WriteVerbose(String.Format("PSModulePath in scope '{0}' is empty.", EnvScope.ToString())); + if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{PathForModules}")) { System.Environment.SetEnvironmentVariable( "PSModulePath", - _path, + PathForModules, + EnvScope + ); + } + } + WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + StringCollection CurrentPSModulePaths = new(); + foreach (string Item in CurrentPSModulePath.Trim(';').Split(';')) { + CurrentPSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); + } + if (CurrentPSModulePaths.Contains(PathForModules)) { + WriteVerbose(String.Format("PSModulePath in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForModules)); + } + else { + WriteVerbose( + String.Format( + "PSModulePath in scope '{0}' does not already contain '{1}'", + EnvScope.ToString(), + PathForModules + ) + ); + if (this.ShouldProcess($"Add '{PathForModules}' to environment variable 'PSModulePath' in scope '{EnvScope}")) + { + System.Environment.SetEnvironmentVariable( + "PSModulePath", + String.Format("{0};{1}", PathForModules, CurrentPSModulePath), + EnvScope + ); + WriteVerbose( + String.Format( + "Successfully added '{0}' to PSModulePath in scope '{1}'", + PathForModules, + EnvScope.ToString() + ) + ); + } + } + + // Add install path override for scripts to PATH + string CurrentPATH = Environment.GetEnvironmentVariable( + "PATH", + EnvScope + ); + if (String.IsNullOrEmpty(CurrentPATH)) { + WriteVerbose(String.Format("PATH in scope '{0}' is empty.", EnvScope.ToString())); + if (this.ShouldProcess($"Set environment pariable 'PATH' in scope '{EnvScope} to '{PathForScripts}")) + { + System.Environment.SetEnvironmentVariable( + "PATH", + PathForScripts, EnvScope ); } } - WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), PSModulePath)); - StringCollection PSModulePaths = new(); - foreach (string Item in PSModulePath.Trim(';').Split(';')) { - PSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); + WriteVerbose(string.Format("Current value of PATH in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + StringCollection CurrentPATHs = new(); + foreach (string Item in CurrentPATH.Trim(';').Split(';')) { + CurrentPATHs.Add(System.Environment.ExpandEnvironmentVariables(Item)); } - if (PSModulePaths.Contains(_path)) { - WriteVerbose(String.Format("Override install path is already in PSModulePath for scope '{0}'", EnvScope.ToString())); + if (CurrentPATHs.Contains(PathForScripts)) { + WriteVerbose(String.Format("PATH in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); } else { WriteVerbose( String.Format( - "Override install path is not already in PSModulePath for scope '{0}'", + "Override install path is not already in Path for scope '{0}'", EnvScope.ToString() ) ); - if (this.ShouldProcess($"Add '{_path}' to environment pariable 'PSModulePath' in scope '{EnvScope}")) + if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'PATH' in scope '{EnvScope}")) { System.Environment.SetEnvironmentVariable( "PSModulePath", - String.Format("{0};{1}", _path, PSModulePath), + String.Format("{0};{1}", PathForScripts, CurrentPATH), EnvScope ); WriteVerbose( String.Format( - "Override install path was successfully added to PSModulePath for scope '{0}'.", + "Successfully added '{0}' to PATH in scope '{1}'", + PathForScripts, EnvScope.ToString() ) ); From d51bdefb33dc74a48b472491b50da46c499025e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:07:07 +0200 Subject: [PATCH 53/60] PATH is named Path --- .../SetPSResourceGetInstallPathOverride.cs | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 68df3881f..0ed68ccaa 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -183,29 +183,29 @@ protected override void ProcessRecord() } } - // Add install path override for scripts to PATH - string CurrentPATH = Environment.GetEnvironmentVariable( - "PATH", + // Add install path override for scripts to Path + string CurrentPath = Environment.GetEnvironmentVariable( + "Path", EnvScope ); - if (String.IsNullOrEmpty(CurrentPATH)) { - WriteVerbose(String.Format("PATH in scope '{0}' is empty.", EnvScope.ToString())); - if (this.ShouldProcess($"Set environment pariable 'PATH' in scope '{EnvScope} to '{PathForScripts}")) + if (String.IsNullOrEmpty(CurrentPath)) { + WriteVerbose(String.Format("Path in scope '{0}' is empty.", EnvScope.ToString())); + if (this.ShouldProcess($"Set environment pariable 'Path' in scope '{EnvScope} to '{PathForScripts}")) { System.Environment.SetEnvironmentVariable( - "PATH", + "Path", PathForScripts, EnvScope ); } } - WriteVerbose(string.Format("Current value of PATH in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); - StringCollection CurrentPATHs = new(); - foreach (string Item in CurrentPATH.Trim(';').Split(';')) { - CurrentPATHs.Add(System.Environment.ExpandEnvironmentVariables(Item)); + WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + StringCollection CurrentPaths = new(); + foreach (string Item in CurrentPath.Trim(';').Split(';')) { + CurrentPaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); } - if (CurrentPATHs.Contains(PathForScripts)) { - WriteVerbose(String.Format("PATH in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); + if (CurrentPaths.Contains(PathForScripts)) { + WriteVerbose(String.Format("Path in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); } else { WriteVerbose( @@ -214,16 +214,16 @@ protected override void ProcessRecord() EnvScope.ToString() ) ); - if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'PATH' in scope '{EnvScope}")) + if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'Path' in scope '{EnvScope}")) { System.Environment.SetEnvironmentVariable( "PSModulePath", - String.Format("{0};{1}", PathForScripts, CurrentPATH), + String.Format("{0};{1}", PathForScripts, CurrentPath), EnvScope ); WriteVerbose( String.Format( - "Successfully added '{0}' to PATH in scope '{1}'", + "Successfully added '{0}' to Path in scope '{1}'", PathForScripts, EnvScope.ToString() ) From 3e243a46dacf1fdd9a9271262e8e548692f89372 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:09:32 +0200 Subject: [PATCH 54/60] Big oops, set Path not PSModulePath for scripts dir --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 0ed68ccaa..1de8efaf4 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -217,7 +217,7 @@ protected override void ProcessRecord() if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'Path' in scope '{EnvScope}")) { System.Environment.SetEnvironmentVariable( - "PSModulePath", + "Path", String.Format("{0};{1}", PathForScripts, CurrentPath), EnvScope ); From 1b2bf3203b60a3f74284b34eb33372c6f201b92b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:12:20 +0200 Subject: [PATCH 55/60] Fixed verbose message --- src/code/SetPSResourceGetInstallPathOverride.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 1de8efaf4..4b2f5d5d9 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -199,7 +199,7 @@ protected override void ProcessRecord() ); } } - WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); + WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPath)); StringCollection CurrentPaths = new(); foreach (string Item in CurrentPath.Trim(';').Split(';')) { CurrentPaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); From be6d63563eb23c3e50f473377a6c4af515d1b31f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Sun, 14 Jul 2024 20:56:10 +0200 Subject: [PATCH 56/60] Simplify some more --- .../SetPSResourceGetInstallPathOverride.cs | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 4b2f5d5d9..09e8706db 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -3,7 +3,6 @@ using Microsoft.PowerShell.PSResourceGet.UtilClasses; using System; -using System.Collections.Specialized; using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; @@ -143,7 +142,7 @@ protected override void ProcessRecord() WriteVerbose(String.Format("PSModulePath in scope '{0}' is empty.", EnvScope.ToString())); if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{PathForModules}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "PSModulePath", PathForModules, EnvScope @@ -151,10 +150,7 @@ protected override void ProcessRecord() } } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); - StringCollection CurrentPSModulePaths = new(); - foreach (string Item in CurrentPSModulePath.Trim(';').Split(';')) { - CurrentPSModulePaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); - } + string[] CurrentPSModulePaths = CurrentPSModulePath.Trim(';').Split(';').Select(s => Environment.ExpandEnvironmentVariables(s)).ToArray(); if (CurrentPSModulePaths.Contains(PathForModules)) { WriteVerbose(String.Format("PSModulePath in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForModules)); } @@ -168,7 +164,7 @@ protected override void ProcessRecord() ); if (this.ShouldProcess($"Add '{PathForModules}' to environment variable 'PSModulePath' in scope '{EnvScope}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "PSModulePath", String.Format("{0};{1}", PathForModules, CurrentPSModulePath), EnvScope @@ -192,7 +188,7 @@ protected override void ProcessRecord() WriteVerbose(String.Format("Path in scope '{0}' is empty.", EnvScope.ToString())); if (this.ShouldProcess($"Set environment pariable 'Path' in scope '{EnvScope} to '{PathForScripts}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "Path", PathForScripts, EnvScope @@ -200,10 +196,7 @@ protected override void ProcessRecord() } } WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPath)); - StringCollection CurrentPaths = new(); - foreach (string Item in CurrentPath.Trim(';').Split(';')) { - CurrentPaths.Add(System.Environment.ExpandEnvironmentVariables(Item)); - } + string[] CurrentPaths = CurrentPath.Trim(';').Split(';').Select(s => Environment.ExpandEnvironmentVariables(s)).ToArray(); if (CurrentPaths.Contains(PathForScripts)) { WriteVerbose(String.Format("Path in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); } @@ -216,7 +209,7 @@ protected override void ProcessRecord() ); if (this.ShouldProcess($"Add '{PathForScripts}' to environment variable 'Path' in scope '{EnvScope}")) { - System.Environment.SetEnvironmentVariable( + Environment.SetEnvironmentVariable( "Path", String.Format("{0};{1}", PathForScripts, CurrentPath), EnvScope From 9b84e8904fea5b0e8f2ad3eb8a269e944b8de432 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Wed, 21 Aug 2024 22:26:58 +0200 Subject: [PATCH 57/60] Remove unneccessary using --- src/code/Utils.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 72e267231..02ec92e86 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -20,7 +20,6 @@ using System.Net.Http; using System.Runtime.InteropServices; using System.Security; -using System.Threading.Tasks; using System.Threading; namespace Microsoft.PowerShell.PSResourceGet.UtilClasses From 71db23c223970460a1ff18bec2e0edefac028f21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Wed, 23 Oct 2024 13:59:19 +0200 Subject: [PATCH 58/60] Format on save --- src/Microsoft.PowerShell.PSResourceGet.psd1 | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.PowerShell.PSResourceGet.psd1 b/src/Microsoft.PowerShell.PSResourceGet.psd1 index f80fab035..d0b841230 100644 --- a/src/Microsoft.PowerShell.PSResourceGet.psd1 +++ b/src/Microsoft.PowerShell.PSResourceGet.psd1 @@ -37,14 +37,14 @@ FunctionsToExport = @( 'Import-PSGetRepository' ) - VariablesToExport = 'PSGetPath' - AliasesToExport = @( + VariablesToExport = 'PSGetPath' + AliasesToExport = @( 'Get-PSResource', 'fdres', 'isres', 'pbres', 'udres') - PrivateData = @{ + PrivateData = @{ PSData = @{ Prerelease = 'RC1' Tags = @('PackageManagement', @@ -66,7 +66,7 @@ - Fix packaging name matching when searching in local repositories (#1731) - `Compress-PSResource` `-PassThru` now passes `FileInfo` instead of string (#1720) -- Fix for `Compress-PSResource` not properly compressing scripts (#1719) +- Fix for `Compress-PSResource` not properly compressing scripts (#1719) - Add `AcceptLicense` to Save-PSResource (#1718 Thanks @o-l-a-v!) - Better support for NuGet v2 feeds (#1713 Thanks @o-l-a-v!) - Better handling of `-WhatIf` support in `Install-PSResource` (#1531 Thanks @o-l-a-v!) @@ -92,7 +92,7 @@ ### New Features -- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, +- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, #1573, #1576, #1587, #1588, #1589, #1594, #1598, #1600, #1602, #1604, #1615) ### Bug Fixes @@ -173,7 +173,7 @@ - Bug fix Artifactory v2 endpoint failures (#1428) - Bug fix Artifactory v3 endpoint failures (#1427) - Bug fix `-RequiredResource` silent failures (#1426) -- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) +- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) See change log (CHANGELOG) at https://github.com/PowerShell/PSResourceGet '@ @@ -181,4 +181,4 @@ See change log (CHANGELOG) at https://github.com/PowerShell/PSResourceGet } HelpInfoUri = 'https://go.microsoft.com/fwlink/?linkid=2238183' -} \ No newline at end of file +} From 7cd3a1b34fb88f4960ec7340dbc3c68f25a4408d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Wed, 23 Oct 2024 13:59:58 +0200 Subject: [PATCH 59/60] Removed unused "using" --- src/code/Utils.cs | 34 ++++++---- src/code/V2ServerAPICalls.cs | 124 ++++++++++++++++++++++------------- 2 files changed, 100 insertions(+), 58 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 04aa3a86f..c684793e6 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -20,7 +20,6 @@ using System.Runtime.InteropServices; using System.Security; using System.Text.RegularExpressions; -using System.Threading.Tasks; using System.Threading; using System; @@ -140,7 +139,8 @@ public static string[] GetStringArrayFromString(string[] delimeter, string strin /// public static string[] GetStringArray(ArrayList list) { - if (list == null) { return null; } + if (list == null) + { return null; } var strArray = new string[list.Count]; for (int i = 0; i < list.Count; i++) @@ -349,7 +349,8 @@ public static bool TryParseVersionOrVersionRange( out VersionRange versionRange) { versionRange = null; - if (version == null) { return false; } + if (version == null) + { return false; } if (version.Trim().Equals("*")) { @@ -1031,8 +1032,9 @@ public static List GetPathsFromEnvVarAndScope( ScopeType? scope) { // Path override is only implemented for Windows so far - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - return GetStandardPathsForScope(psCmdlet,scope); + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return GetStandardPathsForScope(psCmdlet, scope); } // Get value of path override environment variable @@ -1042,10 +1044,12 @@ public static List GetPathsFromEnvVarAndScope( ); // Return standard paths if no override was found, else try to expand paths found in override - if (string.IsNullOrEmpty(pathOverride)) { - return GetStandardPathsForScope(psCmdlet,scope); + if (string.IsNullOrEmpty(pathOverride)) + { + return GetStandardPathsForScope(psCmdlet, scope); } - else { + else + { try { pathOverride = Environment.ExpandEnvironmentVariables(pathOverride); @@ -1053,7 +1057,7 @@ public static List GetPathsFromEnvVarAndScope( catch (ArgumentException) { psCmdlet.WriteWarning("Path override was found, but could not expand environment variable(s). Falling back to standard paths."); - return GetStandardPathsForScope(psCmdlet,scope); + return GetStandardPathsForScope(psCmdlet, scope); } } @@ -1069,8 +1073,9 @@ public static List GetPathsFromEnvVarAndScope( }; return resourcePaths; } - else { - return GetStandardPathsForScope(psCmdlet,scope); + else + { + return GetStandardPathsForScope(psCmdlet, scope); } } @@ -1624,7 +1629,7 @@ public static void DeleteDirectoryWithRestore(string dirPath) public static void DeleteDirectory(string dirPath) { // Remove read only file attributes first - foreach (var dirFilePath in Directory.GetFiles(dirPath,"*",SearchOption.AllDirectories)) + foreach (var dirFilePath in Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)) { if (File.GetAttributes(dirFilePath).HasFlag(FileAttributes.ReadOnly)) { @@ -1638,7 +1643,7 @@ public static void DeleteDirectory(string dirPath) { try { - Directory.Delete(dirPath,true); + Directory.Delete(dirPath, true); return; } catch (Exception ex) @@ -1977,7 +1982,8 @@ public static Collection InvokeScriptWithHost( // Extract expected output types from results pipeline. foreach (var psItem in results) { - if (psItem == null || psItem.BaseObject == null) { continue; } + if (psItem == null || psItem.BaseObject == null) + { continue; } switch (psItem.BaseObject) { diff --git a/src/code/V2ServerAPICalls.cs b/src/code/V2ServerAPICalls.cs index 59b1a3ab4..5108c98c1 100644 --- a/src/code/V2ServerAPICalls.cs +++ b/src/code/V2ServerAPICalls.cs @@ -12,10 +12,7 @@ using System.Xml; using System.Net; using System.Text; -using System.Runtime.ExceptionServices; using System.Management.Automation; -using System.Reflection; -using System.Data.Common; using System.Linq; namespace Microsoft.PowerShell.PSResourceGet.Cmdlets @@ -39,7 +36,7 @@ internal class V2ServerAPICalls : ServerApiCall public override PSRepositoryInfo Repository { get; set; } private readonly PSCmdlet _cmdletPassedIn; private HttpClient _sessionClient { get; set; } - private static readonly Hashtable[] emptyHashResponses = new Hashtable[]{}; + private static readonly Hashtable[] emptyHashResponses = new Hashtable[] { }; public FindResponseType v2FindResponseType = FindResponseType.ResponseString; private bool _isADORepo; private bool _isJFrogRepo; @@ -49,14 +46,14 @@ internal class V2ServerAPICalls : ServerApiCall #region Constructor - public V2ServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base (repository, networkCredential) + public V2ServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base(repository, networkCredential) { this.Repository = repository; _cmdletPassedIn = cmdletPassedIn; HttpClientHandler handler = new HttpClientHandler(); bool token = false; - if(networkCredential != null) + if (networkCredential != null) { token = String.Equals("token", networkCredential.UserName) ? true : false; }; @@ -69,7 +66,9 @@ public V2ServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, N _sessionClient = new HttpClient(handler); _sessionClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); - } else { + } + else + { handler.Credentials = networkCredential; @@ -212,7 +211,7 @@ public override FindResults FindTags(string[] tags, bool includePrerelease, Reso _cmdletPassedIn.WriteDebug($"Count is '{count}'"); // skip 100 scriptSkip += 100; - var tmpResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: false, scriptSkip, out errRecord); + var tmpResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: false, scriptSkip, out errRecord); if (errRecord != null) { return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType); @@ -351,12 +350,14 @@ public override FindResults FindName(string packageName, bool includePrerelease, // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion" : "IsLatestVersion"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -394,7 +395,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, response = string.Empty; } - return new FindResults(stringResponse: new string[]{ response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType); + return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType); } /// @@ -420,12 +421,14 @@ public override FindResults FindNameWithTag(string packageName, string[] tags, b // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion" : "IsLatestVersion"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -646,12 +649,14 @@ public override FindResults FindVersion(string packageName, string version, Reso // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion($"NormalizedVersion eq '{version}'"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -713,12 +718,14 @@ public override FindResults FindVersionWithTag(string packageName, string versio // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion($"NormalizedVersion eq '{version}'"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -908,19 +915,24 @@ private string FindAllFromTypeEndPoint(bool includePrerelease, bool isSearchingM }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } // JFrog/Artifactory requires an empty search term to enumerate all packages in the feed - if (_isJFrogRepo) { + if (_isJFrogRepo) + { queryBuilder.SearchTerm = "''"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } var requestUrlV2 = $"{Repository.Uri}{typeEndpoint}/Search()?{queryBuilder.BuildQueryString()}"; @@ -948,19 +960,24 @@ private string FindTagFromEndpoint(string[] tags, bool includePrerelease, bool i }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } // JFrog/Artifactory requires an empty search term to enumerate all packages in the feed - if (_isJFrogRepo) { + if (_isJFrogRepo) + { queryBuilder.SearchTerm = "''"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } @@ -990,14 +1007,18 @@ private string FindCommandOrDscResource(string[] tags, bool includePrerelease, b }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } @@ -1032,19 +1053,23 @@ private string FindNameGlobbing(string packageName, ResourceType type, bool incl }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } - var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries); + var names = packageName.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); if (names.Length == 0) { @@ -1103,7 +1128,8 @@ private string FindNameGlobbing(string packageName, ResourceType type, bool incl return string.Empty; } - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } var requestUrlV2 = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}"; @@ -1127,19 +1153,23 @@ private string FindNameGlobbingWithTag(string packageName, string[] tags, Resour }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } - var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries); + var names = packageName.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); if (!_isPSGalleryRepo) { @@ -1203,7 +1233,8 @@ private string FindNameGlobbingWithTag(string packageName, string[] tags, Resour filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true"); } - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } var requestUrlV2 = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}"; @@ -1276,7 +1307,8 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange { maxPart = String.Format(format, operation, $"'{maxVersion.ToNormalizedString()}'"); } - else { + else + { maxPart = String.Format(format, operation, $"'{versionRange.MaxVersion.ToNormalizedString()}'"); } } @@ -1290,7 +1322,8 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange { filterBuilder.AddCriterion(maxPart); } - if (!includePrerelease) { + if (!includePrerelease) + { filterBuilder.AddCriterion("IsPrerelease eq false"); } @@ -1298,11 +1331,13 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } - if (type == ResourceType.Script) { + if (type == ResourceType.Script) + { filterBuilder.AddCriterion($"substringof('PS{type.ToString()}', Tags) eq true"); } @@ -1361,7 +1396,8 @@ private Stream InstallVersion(string packageName, string version, out ErrorRecor return response.ReadAsStreamAsync().Result; } - private string GetTypeFilterForRequest(ResourceType type) { + private string GetTypeFilterForRequest(ResourceType type) + { string typeFilterPart = string.Empty; if (type == ResourceType.Script) { @@ -1414,7 +1450,7 @@ public int GetCountFromResponse(string httpResponse, out ErrorRecord errRecord) if (!countSearchSucceeded) { - // Note: not all V2 servers may have the 'count' property implemented or valid (i.e CloudSmith server), in this case try to get 'd:Id' property. + // Note: not all V2 servers may have the 'count' property implemented or valid (i.e CloudSmith server), in this case try to get 'd:Id' property. elemList = doc.GetElementsByTagName("d:Id"); if (elemList.Count > 0) { From 3b9ed218ef21b6acfc8390789d0e2c6df66a4052 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olav=20R=C3=B8nnestad=20Birkeland?= <6450056+o-l-a-v@users.noreply.github.com> Date: Wed, 23 Oct 2024 14:05:56 +0200 Subject: [PATCH 60/60] Remove unused using and run formatting --- src/code/GetInstalledPSResource.cs | 2 +- src/code/ServerApiCall.cs | 7 ++-- .../SetPSResourceGetInstallPathOverride.cs | 35 ++++++++++++------- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/src/code/GetInstalledPSResource.cs b/src/code/GetInstalledPSResource.cs index fc30d5eb6..c66c2df03 100644 --- a/src/code/GetInstalledPSResource.cs +++ b/src/code/GetInstalledPSResource.cs @@ -118,7 +118,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { - var namesToSearch = Utils.ProcessNameWildcards(Name, removeWildcardEntries:false, out string[] errorMsgs, out bool _); + var namesToSearch = Utils.ProcessNameWildcards(Name, removeWildcardEntries: false, out string[] errorMsgs, out bool _); foreach (string error in errorMsgs) { WriteError(new ErrorRecord( diff --git a/src/code/ServerApiCall.cs b/src/code/ServerApiCall.cs index 1ae1f02d6..bca013dcb 100644 --- a/src/code/ServerApiCall.cs +++ b/src/code/ServerApiCall.cs @@ -8,7 +8,6 @@ using System.Management.Automation; using System.Net; using System.Net.Http; -using System.Runtime.ExceptionServices; using System.Text; @@ -32,7 +31,7 @@ public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCrede HttpClientHandler handler = new HttpClientHandler(); bool token = false; - if(networkCredential != null) + if (networkCredential != null) { token = String.Equals("token", networkCredential.UserName) ? true : false; }; @@ -44,7 +43,9 @@ public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCrede _sessionClient = new HttpClient(handler); _sessionClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); - } else { + } + else + { handler.Credentials = networkCredential; diff --git a/src/code/SetPSResourceGetInstallPathOverride.cs b/src/code/SetPSResourceGetInstallPathOverride.cs index 09e8706db..888dcb652 100644 --- a/src/code/SetPSResourceGetInstallPathOverride.cs +++ b/src/code/SetPSResourceGetInstallPathOverride.cs @@ -61,7 +61,8 @@ out ProviderInfo provider protected override void BeginProcessing() { // Only run on Windows for now, due to env variables on Unix being very different - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { ThrowTerminatingError( new ErrorRecord( new PSInvalidOperationException($"Error this only works on Windows for now"), @@ -81,15 +82,16 @@ protected override void ProcessRecord() { // Assets EnvironmentVariableTarget EnvScope = (Scope is ScopeType.AllUsers) ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; - string PathForModules = System.IO.Path.Combine(_path,"Modules"); - string PathForScripts = System.IO.Path.Combine(_path,"Scripts"); + string PathForModules = System.IO.Path.Combine(_path, "Modules"); + string PathForScripts = System.IO.Path.Combine(_path, "Scripts"); // Set env variable for install path override string PathOverrideCurrentValue = Environment.GetEnvironmentVariable( "PSResourceGetInstallPathOverride", EnvScope ); - if (!String.IsNullOrEmpty(PathOverrideCurrentValue)) { + if (!String.IsNullOrEmpty(PathOverrideCurrentValue)) + { WriteVerbose( String.Format( "Current value of PSResourceGetInstallPathOverride in scope '{0}': '{1}'", @@ -115,7 +117,8 @@ protected override void ProcessRecord() ) ); } - else { + else + { if (this.ShouldProcess($"Set environment variable PSResourceGetPathOverride in scope '{EnvScope} to '{_path}")) { Environment.SetEnvironmentVariable( @@ -138,7 +141,8 @@ protected override void ProcessRecord() "PSModulePath", EnvScope ); - if (String.IsNullOrEmpty(CurrentPSModulePath)) { + if (String.IsNullOrEmpty(CurrentPSModulePath)) + { WriteVerbose(String.Format("PSModulePath in scope '{0}' is empty.", EnvScope.ToString())); if (this.ShouldProcess($"Set environment pariable 'PSModulePath' in scope '{EnvScope} to '{PathForModules}")) { @@ -151,10 +155,12 @@ protected override void ProcessRecord() } WriteVerbose(string.Format("Current value of PSModulePath in {0} context: '{1}'", EnvScope.ToString(), CurrentPSModulePath)); string[] CurrentPSModulePaths = CurrentPSModulePath.Trim(';').Split(';').Select(s => Environment.ExpandEnvironmentVariables(s)).ToArray(); - if (CurrentPSModulePaths.Contains(PathForModules)) { - WriteVerbose(String.Format("PSModulePath in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForModules)); + if (CurrentPSModulePaths.Contains(PathForModules)) + { + WriteVerbose(String.Format("PSModulePath in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(), PathForModules)); } - else { + else + { WriteVerbose( String.Format( "PSModulePath in scope '{0}' does not already contain '{1}'", @@ -184,7 +190,8 @@ protected override void ProcessRecord() "Path", EnvScope ); - if (String.IsNullOrEmpty(CurrentPath)) { + if (String.IsNullOrEmpty(CurrentPath)) + { WriteVerbose(String.Format("Path in scope '{0}' is empty.", EnvScope.ToString())); if (this.ShouldProcess($"Set environment pariable 'Path' in scope '{EnvScope} to '{PathForScripts}")) { @@ -197,10 +204,12 @@ protected override void ProcessRecord() } WriteVerbose(string.Format("Current value of Path in {0} context: '{1}'", EnvScope.ToString(), CurrentPath)); string[] CurrentPaths = CurrentPath.Trim(';').Split(';').Select(s => Environment.ExpandEnvironmentVariables(s)).ToArray(); - if (CurrentPaths.Contains(PathForScripts)) { - WriteVerbose(String.Format("Path in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(),PathForScripts)); + if (CurrentPaths.Contains(PathForScripts)) + { + WriteVerbose(String.Format("Path in scope '{0}' already contains '{1}', no change needed.", EnvScope.ToString(), PathForScripts)); } - else { + else + { WriteVerbose( String.Format( "Override install path is not already in Path for scope '{0}'",