You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add -PreservePathFrom dynamic parameter to Copy-Item and Move-Item - #28467
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.
./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.
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.
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.
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.
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.
- 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.
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.
- 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.
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.
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.
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.
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
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.
PR Summary
Add a new dynamic parameter
-PreservePathFromto theFileSystemprovider that is surfaced inCopy-ItemandMove-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../logs/sub1/deep/d.logis copied to./export/sub1/deep/d.loginstead of being flattened into./export/d.log. The same parameter is available onMove-Item.PR Context
Fixes #26161.
Today, piping filtered items into
Copy-Item/Move-Itemflattens them into the destination directory, andMove-Itemto a non-existing destination repeatedly fails after the first item. The Engine WG discussed this in #26161 (comment) and decided to keep filtering inWhere-Object(rather than extending-Filterwith script blocks), but to accept a dynamic parameter for theFileSystemprovider, surfaced inCopy-ItemandMove-Item, that specifies the base path to preserve structure from. This PR implements that decision.Implementation notes:
CopyItemDynamicParametersgained aPreservePathFromproperty and a newMoveItemDynamicParametersclass was added forMove-Item(FileSystemProvider.MoveItemDynamicParametersoverride).FileSystemdirectory), computes the item's path relative to it viaPath.GetRelativePath, and adjusts the destination accordingly. Missing destination directories are created as needed, honoringShouldProcess(nothing is created for-WhatIf).PreservePathFromOutsideBasePath), so pipeline input with mixed items keeps processing.-FromSession/-ToSessionand writes an error in that case.-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
.h,.cpp,.cs,.ps1and.psm1files have the correct copyright header