Skip to content

Add -PreservePathFrom dynamic parameter to Copy-Item and Move-Item - #28467

Open
soroshsabz wants to merge 3 commits into
PowerShell:masterfrom
soroshsabz:preserve-path-from
Open

soroshsabz wants to merge 3 commits into
PowerShell:masterfrom
soroshsabz:preserve-path-from

Conversation

@soroshsabz

@soroshsabz soroshsabz commented Nov 20, 2026 •

Copy link
Copy Markdown

PR Summary

Add a new dynamic parameter -PreservePathFrom to the FileSystem provider that is surfaced in Copy-Item and Move-Item. It specifies the base path from which the relative path of each item is preserved at the destination, so that filtered items can be copied or moved while keeping their folder structure.

Get-ChildItem ./logs -File -Recurse
    | Where-Object LastWriteTime -gt ([System.DateTime]::Today.AddDays(-30))
    | Copy-Item -PreservePathFrom ./logs -Destination ./export

./logs/sub1/deep/d.log is copied to ./export/sub1/deep/d.log instead of being flattened into ./export/d.log. The same parameter is available on Move-Item.

PR Context

Fixes #26161.

Today, piping filtered items into Copy-Item/Move-Item flattens them into the destination directory, and Move-Item to a non-existing destination repeatedly fails after the first item. The Engine WG discussed this in #26161 (comment) and decided to keep filtering in Where-Object (rather than extending -Filter with script blocks), but to accept a dynamic parameter for the FileSystem provider, surfaced in Copy-Item and Move-Item, that specifies the base path to preserve structure from. This PR implements that decision.

Implementation notes:

  • CopyItemDynamicParameters gained a PreservePathFrom property and a new MoveItemDynamicParameters class was added for Move-Item (FileSystemProvider.MoveItemDynamicParameters override).
  • When the parameter is bound, the provider resolves the base path (it must resolve to a single existing FileSystem directory), computes the item's path relative to it via Path.GetRelativePath, and adjusts the destination accordingly. Missing destination directories are created as needed, honoring ShouldProcess (nothing is created for -WhatIf).
  • Items that are not below the base path (including items on another root) write a non-terminating error (PreservePathFromOutsideBasePath), so pipeline input with mixed items keeps processing.
  • The parameter is not supported together with -FromSession/-ToSession and writes an error in that case.
  • Works with piped files, piped directories, and wildcard paths; interacts correctly with -Recurse, -PassThru, -LiteralPath, and self-copy/self-move detection.

The parameter name follows the name used in the working group discussion; happy to rename if the reviewers prefer something else.

PR Checklist

Add a dynamic parameter to the FileSystem provider that is surfaced in
Copy-Item and Move-Item to preserve the folder structure of the items
being copied or moved, relative to a specified base path.

This enables filtering items with Get-ChildItem / Where-Object and then
copying or moving them while keeping their relative paths:

    Get-ChildItem ./logs -File -Recurse
        | Where-Object LastWriteTime -gt ([System.DateTime]::Today.AddDays(-30))
        | Copy-Item -PreservePathFrom ./logs -Destination ./export

When the parameter is specified, the destination for each item is
adjusted by its relative path below the base path and the required
destination directories are created as needed. Items that are not below
the base path produce a non-terminating error. The parameter cannot be
combined with -FromSession or -ToSession.
@soroshsabz
soroshsabz requested a review from a team as a code owner November 20, 2026 13:56
Copilot AI balanced review requested due to automatic review settings November 20, 2026 13:56
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved path-preservation bugs can skip valid copies, duplicate directory nesting at existing destinations, and modify the source tree before rejecting an invalid move.

3 open issues
What changed in this PR

Adds the FileSystem provider’s -PreservePathFrom dynamic parameter to Copy-Item and Move-Item, addressing #26161 by preserving folder structure for filtered items without extending -Filter.

Changes:

  • Calculates destinations relative to a specified base directory and creates missing parent directories.
  • Adds validation and error messages for invalid base paths, outside-base items, and unsupported remoting combinations.
  • Adds tests for preserved paths, validation errors, and selected command options.
File Description
test/​powershell/​Modules/​Microsoft.PowerShell.Management/​Move-Item.Tests.ps1 Tests preserved moves and invalid base paths.
test/​powershell/​Modules/​Microsoft.PowerShell.Management/​Copy-Item.Tests.ps1 Tests preserved copies, wildcards, -PassThru, validation, and -WhatIf.
src/​System.Management.Automation/​resources/​FileSystemProviderStrings.resx Adds parameter validation error messages.
src/​System.Management.Automation/​namespaces/​FileSystemProvider.cs Implements dynamic parameters and shared destination calculation.

Review effort: Balanced

- Resolve the base path with an isolated CmdletProviderContext so the
  Include, Exclude, and Filter settings of the copy or move operation
  are no longer applied to the base directory while it is resolved.
- Make the preserved destination calculation side-effect free. The
  parent of the destination is now created by the copy and move code
  paths once the operation has been validated and confirmed, so
  rejected operations (for example, moving a directory into its own
  sub-directory) no longer leave newly created directories behind.
  -WhatIf no longer previews directory creation either; it only shows
  the item operations with their full preserved destination paths.
- Treat preserved destinations as exact targets. The item name is no
  longer appended again when the target already exists, fixing doubled
  nesting such as export/Sub1/Sub1 for both Copy-Item and Move-Item,
  while recursive child copies keep their regular semantics.

Add regression tests for the -Include interaction, rejected moves, and
existing target directories.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Base-path resolution fails to restore the provider’s operation context, potentially allowing copy/move operations to bypass -WhatIf and lose output/error streaming and filters.

1 open issue
3 resolved since last review

Review effort: Balanced

- Save the context of the running operation and restore it after the
  base path is resolved, so the provider cannot be left running on the
  temporary resolution context even if the path resolution were to
  install it through provider callbacks.
- Remove the temporary resolution context from the stop referrals of
  the operation context; it was previously retained for every item,
  accumulating dead contexts across pipeline records.
- Always glob the base path argument. The temporary context inherited
  SuppressWildcardExpansion from the operation context, which is set
  when the Path parameter is bound from pipeline input (pipeline paths
  are treated as literal), so wildcard base paths like '.\log*' failed
  with Cannot find path when items were piped in.
- Forward errors that the path resolution accumulates on the temporary
  context to the operation context instead of dropping them.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved defects can overwrite existing files during recursive copies and delete source files during forced moves, while per-item wildcard resolution can also invalidate the base mid-operation.

1 open issue
2 previously missed issues

In code that hasn't changed since last review

High severity Reject file targets before copying directory contents

src/​System.Management.Automation/​namespaces/​FileSystemProvider.cs:4077

If export/Sub1 is an existing file, Copy-Item logs/Sub1 -PreservePathFrom logs -Destination export -Recurse reports a directory-creation error but continues copying children, overwriting that file with a child's contents. Reject an adjusted directory target that is an existing file before recursing, and add a regression test asserting that its contents remain unchanged.

High severity Reject same-item move targets before forced retry

src/​System.Management.Automation/​namespaces/​FileSystemProvider.cs:6166

On Windows, Move-Item ./logs/a.log -PreservePathFrom ./logs -Destination ./logs -Force adjusts the target to the source file itself. When FileInfo.MoveTo fails, the forced retry deletes the destination—which is also the source—causing data loss. Reject same-item adjusted destinations before calling the move helpers, using the identity check already used by CopyItem, and add a regression test that verifies the source survives.

1 resolved since last review

Review effort: Balanced

Comment on lines +3631 to +3634
resolvedBasePaths = Context.ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath(
preservePathFrom,
resolutionContext,
out baseProvider);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Add parameter to Copy-Item/Move-Item to preserve folder structure

2 participants