Skip to content

Document Copy-Item's behavior when wildcard matching is performed and -Destination doesn't exist #12621

@surfingoldelephant

Description

@surfingoldelephant

Prerequisites

  • Existing Issue: Search the existing issues for this repository. If there is an issue that fits your needs do not file a new one. Subscribe, react, or comment on that issue instead.
  • Descriptive Title: Write the title for this issue as a short synopsis. If possible, provide context. For example, "Typo in Get-Foo cmdlet" instead of "Typo."
  • Verify Version: If there is a mismatch between documentation and the behavior on your system, ensure that the version you are using is the same as the documentation. Check this box if they match or the issue you are reporting is not version specific.

Links

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item

Summary

Copy-Item's behavior in the following scenario is not currently documented:

  • The -Path directory only contains files.
  • Wildcard matching is performed.
  • -Destination doesn't already exist.

Details

When wildcard matching is performed and -Destination doesn't already exist, it's the first discovered source item that dictates whether -Destination becomes a file or directory.

Therefore, if only files are discovered, the destination will end up being a single file that happens to be whichever source file was discovered last (as each file overwrites the previous). To demonstrate the issue:

$source = "$env:TEMP\source"; $destination = "$env:TEMP\destination"

Remove-Item -LiteralPath $destination -ErrorAction Ignore
[void] (1..3 | New-Item -Path $source -Name { "$_.txt" } -ItemType File -Force)

Copy-Item -Path $source\* -Destination $destination

(Get-Item -LiteralPath $destination).GetType().FullName # System.IO.FileInfo

Notes:


This is the current Copy-Item Example 2:

# Example 2: Copy directory contents to an existing directory
Copy-Item -Path "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse

Whilst the example is based on the destination directory already existing, it does include the following note:

If the path C:\Drawings doesn't exist the cmdlet copies all the files from the Logfiles folder tree into a single folder C:\Drawings, overwriting any files with the same name.

The note is inaccurate in scenarios where C:\Logfiles only contains files.

Suggested Fix

Emphasize the importance of ensuring that the -Destination directory already exists if wildcards are used in -Path.

Metadata

Metadata

Assignees

No one assigned

    Labels

    issue-doc-bugIssue - error in documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions