Forum Discussion

balubeto's avatar
balubeto
Brass Contributor
Oct 21, 2022

Problem with CopyItem cmdlet

Hi

 

I use PowerShell 7.x on Windows 11 Update.

 

I should copy all the txt files from the Test1 directory to the Test2 directory.

I tried writing

 

 

Copy-Item -Path .\Test1\ -Filter *.txt -Destination .\Test2\

 

 

but, in the destination directory, the source directory is created instead of copying the txt files. How come?

 

Thanks

 

Bye

  • balubeto 

     

    The source path requires a wildcard at the end as shown below. Without this wildcard, the command will copy the directory object only, not the child content.

     

    Copy-Item -Path .\Test1\* -Filter *.txt -Destination .\Test2\

     

    Cheers,

    Lain

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    balubeto 

     

    The source path requires a wildcard at the end as shown below. Without this wildcard, the command will copy the directory object only, not the child content.

     

    Copy-Item -Path .\Test1\* -Filter *.txt -Destination .\Test2\

     

    Cheers,

    Lain

    • balubeto's avatar
      balubeto
      Brass Contributor

      I put some txt files in the working directory and created two subdirectories Test1 and Test2.

       

      Afterwards, I wrote

       

      Copy-Item -path .\* -Filter *.txt -Destination .\Test?\

       

      but it gives me error.

       

      Instead, if I write the two commands ,

       

      Copy-Item -path .\* -Filter *.txt -Destination .\Test1\
      Copy-Item -path .\* -Filter *.txt -Destination .\Test2\

       

      the txt files are copied to both directories.

       

      So, why does the wildcard not work?

       

      Thanks

       

      Bye

      • LainRobertson's avatar
        LainRobertson
        Silver Contributor

        balubeto 

         

        If you take a look at the commandlet reference below, you'll notice that that the "-Path" parameter states you can use wildcards while the "-Destination" parameter does not.

         

        You'll also notice that "-Path" is a string array (shown as "string[]") where "-Destination" is only a single-valued string.

         

        So, in terms of what these combinations allow and don't allow:

         

        • Path accepts multiple source strings which can include wildcards;
        • Destination only accepts a single destination string and no wildcards.

         

        Reference:

         

         

        If you want to copy a given set of files to multiple destinations then you will have to do exactly what you said, which is use multiple Copy-Item statements.

         

        Cheers,

        Lain

Resources