-
Notifications
You must be signed in to change notification settings - Fork 8.4k
Add PSContentPath Infrastructure #26509
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jshigetomi
wants to merge
52
commits into
PowerShell:master
Choose a base branch
from
jshigetomi:PSModulePathFix
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
52 commits
Select commit
Hold shift + click to select a range
b73eea5
Testing
805fd0e
Update PSModulePath
6dc662d
Add Experimental feature for PSContent
jshigetomi 67a18aa
Merge branch 'master' into PSModulePathFix
jshigetomi 4a7bb3d
Removed unused variables
jshigetomi 00b6307
Switch to default PSContentPath LOCALAPPData, cmdlets added
jshigetomi 7e5802b
Add lazy migration
jshigetomi 830016e
Add null checks incase PSUserContentPath fails to get any value
jshigetomi 56acf2d
Able to use expanded environmental variables
jshigetomi 3f5709d
Remove help URI
jshigetomi 9e516fa
Reassign perUserConfigDirectory if experimental feature is enabled wh…
jshigetomi d371979
Move migration to GetPSContentPath API, added safety fallbacks to def…
jshigetomi c62f82a
Merge branch 'master' into PSModulePathFix
jshigetomi b207b5c
Add tests
jshigetomi 8fc45c7
Merge branch 'PSModulePathFix' of https://github.com/jshigetomi/Power…
jshigetomi fb2036c
Merge branch 'master' into PSModulePathFix
jshigetomi eaaaedd
Add initial test cases for PSContentPath
jshigetomi eed1cf3
Fix expanding env variable test
jshigetomi ec18785
Separate commands for env var test
jshigetomi c37e776
Initial redo to remove experimental feature aspect and point to OneDr…
jshigetomi f01f00f
Switch default PSContentPath variable to OneDrive
jshigetomi b567218
Remove old PSUserContentPath code
jshigetomi c70f885
Fix help test and add Get/Set to cmdlet test
jshigetomi 1bc5dbc
Update tab completion tests with PSContentPath resolution
jshigetomi 2cefe89
Add warning message in tabcompletion tests
jshigetomi c639721
Remove changes to build script
jshigetomi c04a5ef
Add Move-PSContentPath cmdlet
jshigetomi c4fa79b
Skip Move-PSContentPath in HelpSystem tests for now
jshigetomi 2c58858
Separate out fallback resolution for UNIX/Windows
jshigetomi cd55051
Add Move-PSContent to cmdlets list and clean up code
jshigetomi c83004f
Merge branch 'master' into PSModulePathFix
jshigetomi 3342865
Add back switch-process
jshigetomi 4986975
Merge branch 'PSModulePathFix' of https://github.com/jshigetomi/Power…
jshigetomi 960951e
Changes from Copilot review
7cfca95
Fix Set-PSContentPath logic, add summary for Get-PSContentPath
26d3b69
Add PSUserContentPath as a pwsh variable, Remove Move-PSContentPath
jshigetomi fcc449f
Make LocalAppData default config file location
jshigetomi 859b3ba
Add PSUSerContentVariable class to emit custom error message, Fix tes…
jshigetomi b2d5d3f
Point test fixutre at new locaiton for config LocalAppData
jshigetomi ff76bf4
Merge branch 'master' into PSModulePathFix
jshigetomi 4c351a8
Add -ConfigFile parameter to Get-PSContentPath, -WhatIf
jshigetomi 3990e6c
Add both paths to PSModulePath
jshigetomi fd9d8ec
Rename to PSContentCommands
jshigetomi d69bb03
Add config file as a note property and rename -reset parameter to def…
jshigetomi 95ec9f8
Change impact for Set-PSContentPath to High
jshigetomi b212b12
Copilot review fixes
cdd6313
Add in necessary directives
2eace0b
- Add null check for GetPersonalModulePath.
740ef74
Remove readonly for PSUserContentPath and rely on setter to throw a h…
f8459dc
Remove tests for helpful error message
5902fb4
Remove deduplicatation test because tests inject module path
ab4feea
Merge branch 'master' into PSModulePathFix
jshigetomi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
261 changes: 261 additions & 0 deletions
261
src/System.Management.Automation/engine/Configuration/PSContentCommands.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,261 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System; | ||
| using System.IO; | ||
| using System.Management.Automation; | ||
| using System.Management.Automation.Configuration; | ||
| using System.Management.Automation.Internal; | ||
|
|
||
| namespace Microsoft.PowerShell.Commands | ||
| { | ||
| /// <summary> | ||
| /// Implements Get-PSContentPath cmdlet. | ||
| /// </summary> | ||
| [Cmdlet(VerbsCommon.Get, "PSContentPath", HelpUri = "https://go.microsoft.com/fwlink/?linkid=2344910")] | ||
| [OutputType(typeof(DirectoryInfo))] | ||
| public class GetPSContentPathCommand : PSCmdlet | ||
| { | ||
| /// <summary> | ||
| /// EndProcessing method of this cmdlet. | ||
| /// Outputs the PSContentPath as a DirectoryInfo object with ConfigFile NoteProperty. | ||
| /// </summary> | ||
| protected override void EndProcessing() | ||
| { | ||
| try | ||
| { | ||
| var psContentPath = Utils.GetPSContentPath(); | ||
| var configFilePath = PowerShellConfig.Instance.GetConfigFilePath(ConfigScope.CurrentUser); | ||
|
|
||
| // Create DirectoryInfo object | ||
| var directoryInfo = new DirectoryInfo(psContentPath); | ||
|
|
||
| // Wrap in PSObject to add the ConfigFile NoteProperty | ||
| var result = PSObject.AsPSObject(directoryInfo); | ||
| result.Properties.Add(new PSNoteProperty("ConfigFile", configFilePath)); | ||
|
|
||
| WriteObject(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| ex, | ||
| "GetPSContentPathFailed", | ||
| ErrorCategory.ReadError, | ||
| null)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Implements Set-PSContentPath cmdlet. | ||
| /// </summary> | ||
| [Cmdlet(VerbsCommon.Set, "PSContentPath", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High, HelpUri = "https://go.microsoft.com/fwlink/?linkid=2344807")] | ||
| public class SetPSContentPathCommand : PSCmdlet | ||
| { | ||
| private const string RestartWarning = "Restart PowerShell for the content path change to take full effect on module paths, profiles, help files, and scripts."; | ||
| /// <summary> | ||
| /// Gets or sets the PSContentPath to configure. | ||
| /// </summary> | ||
| [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Path")] | ||
| [ValidateNotNullOrEmpty] | ||
| public string Path { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Resets the PSContentPath to the platform default. | ||
| /// </summary> | ||
| [Parameter(Mandatory = true, ParameterSetName = "Default")] | ||
| public SwitchParameter Default { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// EndProcessing method of this cmdlet. | ||
| /// Validates the path and sets the PSContentPath in the configuration. | ||
| /// </summary> | ||
| protected override void EndProcessing() | ||
| { | ||
| if (Default) | ||
| { | ||
| ResetToDefault(); | ||
| return; | ||
| } | ||
|
|
||
| // Validate the path | ||
| if (!ValidatePath(Path)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| string expandedPath = Environment.ExpandEnvironmentVariables(Path); | ||
| string currentPath = Utils.GetPSContentPath(); | ||
| string configFile = PowerShellConfig.Instance.GetConfigFilePath(ConfigScope.CurrentUser); | ||
|
|
||
| string target = $"Config file: '{configFile}'"; | ||
| string action = $"Set PSUserContentPath from '{currentPath}' to '{expandedPath}'"; | ||
|
|
||
| if (ShouldProcess(target, action)) | ||
| { | ||
| try | ||
| { | ||
| PowerShellConfig.Instance.SetPSContentPath(Path); | ||
|
|
||
| // Update the $PSUserContentPath readonly variable in the current session | ||
| UpdatePSUserContentPathVariable(expandedPath); | ||
|
|
||
|
jshigetomi marked this conversation as resolved.
|
||
| WriteWarning(RestartWarning); | ||
| WriteVerbose($"Successfully set PSContentPath to '{Path}'"); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| ex, | ||
| "SetPSContentPathFailed", | ||
| ErrorCategory.WriteError, | ||
| Path)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Resets the PSContentPath to the platform default by clearing the custom config. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Currently resets to Documents\PowerShell (LegacyPSContentDirectory) for backward compatibility. | ||
| /// In a future release, this will change to LocalAppData\PowerShell as the default content directory. | ||
| /// </remarks> | ||
| private void ResetToDefault() | ||
| { | ||
| string defaultPath = Platform.LegacyPSContentDirectory; | ||
| string currentPath = Utils.GetPSContentPath(); | ||
| string configFile = PowerShellConfig.Instance.GetConfigFilePath(ConfigScope.CurrentUser); | ||
|
|
||
| string target = $"Config file: '{configFile}'"; | ||
| string action = $"Reset PSUserContentPath from '{currentPath}' to platform default '{defaultPath}'"; | ||
|
|
||
| if (ShouldProcess(target, action)) | ||
| { | ||
| try | ||
| { | ||
| // Clear the custom path from config (passing null/empty removes the key) | ||
| PowerShellConfig.Instance.SetPSContentPath(null); | ||
|
|
||
| // Update the variable to the platform default | ||
| UpdatePSUserContentPathVariable(defaultPath); | ||
|
|
||
| WriteWarning(RestartWarning); | ||
| WriteVerbose($"Successfully reset PSContentPath to default: '{defaultPath}'"); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| ex, | ||
| "ResetPSContentPathFailed", | ||
| ErrorCategory.WriteError, | ||
| null)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Updates the $PSUserContentPath readonly variable in the current session. | ||
| /// </summary> | ||
| /// <param name="newPath">The new path value to set.</param> | ||
| private void UpdatePSUserContentPathVariable(string newPath) | ||
| { | ||
| // Get the existing PSUserContentPathVariable and update its internal value | ||
| var existingVariable = SessionState.PSVariable.Get(SpecialVariables.PSUserContentPath); | ||
| if (existingVariable is PSUserContentPathVariable contentPathVariable) | ||
| { | ||
| contentPathVariable.UpdateValue(newPath); | ||
| } | ||
| else | ||
| { | ||
| // Fallback: create a new PSUserContentPathVariable (shouldn't normally happen) | ||
| var variable = new PSUserContentPathVariable(newPath); | ||
| SessionState.Internal.SetVariableAtScope(variable, "global", force: true, CommandOrigin.Internal); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Validates that the provided path is a valid directory path. | ||
| /// </summary> | ||
| /// <param name="path">The path to validate.</param> | ||
| /// <returns>True if the path is valid, false otherwise.</returns> | ||
| private bool ValidatePath(string path) | ||
| { | ||
| try | ||
| { | ||
| // Expand environment variables if present | ||
| string expandedPath = Environment.ExpandEnvironmentVariables(path); | ||
|
|
||
| // Check if the path contains invalid characters using PowerShell's existing utility | ||
| if (PathUtils.ContainsInvalidPathChars(expandedPath)) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| new ArgumentException($"The path '{path}' contains invalid characters."), | ||
| "InvalidPathCharacters", | ||
| ErrorCategory.InvalidArgument, | ||
| path)); | ||
| return false; | ||
| } | ||
|
|
||
| // Check if the path is rooted (absolute path) | ||
| if (!System.IO.Path.IsPathRooted(expandedPath)) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| new ArgumentException($"The path '{path}' must be an absolute path."), | ||
| "RelativePathNotAllowed", | ||
| ErrorCategory.InvalidArgument, | ||
| path)); | ||
| return false; | ||
| } | ||
|
|
||
| // Try to get the full path to validate format | ||
| string fullPath = System.IO.Path.GetFullPath(expandedPath); | ||
|
|
||
| // Warn if the directory doesn't exist, but don't fail | ||
| if (!Directory.Exists(fullPath)) | ||
| { | ||
| WriteWarning($"The directory '{fullPath}' does not exist. It will be created when needed."); | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
| catch (ArgumentException ex) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| ex, | ||
| "InvalidPathFormat", | ||
| ErrorCategory.InvalidArgument, | ||
| path)); | ||
| return false; | ||
| } | ||
| catch (System.Security.SecurityException ex) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| ex, | ||
| "PathAccessDenied", | ||
| ErrorCategory.PermissionDenied, | ||
| path)); | ||
| return false; | ||
| } | ||
| catch (NotSupportedException ex) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| ex, | ||
| "PathNotSupported", | ||
| ErrorCategory.InvalidArgument, | ||
| path)); | ||
| return false; | ||
| } | ||
| catch (PathTooLongException ex) | ||
| { | ||
| WriteError(new ErrorRecord( | ||
| ex, | ||
| "PathTooLong", | ||
| ErrorCategory.InvalidArgument, | ||
| path)); | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.