How to copy files of the specific extension using PowerShell?


To copy the files using the specific files extension using PowerShell, we can use the Copy-Item command.

The below command will copy only the .ps1 files from the source to the destination.

For example,

PS C:\> Copy-Item -Path C:\Temp -Recurse -Filter *.ps1 -Destination C:\Temp1\ -Verbose

If the C:\Temp1 doesn't exist, it will create the destination folder and then copy the content of the file but the problem with this command is it copies the subfolders as well which doesn’t have the .ps1 file.

So to copy the with the same folder structure without empty directories and the specific file extension we can write the code to check the size of the directory after copy and delete if the folder is empty but this would be a lengthy process.

We can use the xCopy or the RoboCopy command to overcome the above problem.

PS C:\> robocopy c:\temp c:\temp1 "*.ps1" /s

The above command will copy files with extension .ps1 from the C:\temp to the C:\temp1 without the empty folders.

Updated on: 17-May-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements