Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file to multiple folders in PowerShell

I am running a script that has multiple environments in it that can be selected from a window that pops up. the only problem I have run into is when I want to set up the script to copy from a source function that I have created and put it into multiple locations at once.

The part of the code I need help with is posted below.

$Source = Select-Boss

$destination = 'D:\parts','D:\labor','D:\time','D:\money'

"Calling Copy-Item with parameters source: '$source', destination: '$destination'."

Copy-Item -Path $source -Destination $destination

The section below is how the rest of the copy functions are set up in the script, so you have a better understanding of what the main section copies are.

$Source = Select-Boss

$destination = 'D:\parts'

"Calling Copy-Item with parameters source: '$source', destination: '$destination'."

Copy-Item -Path $source -Destination $destination

But for one specific part I need to have it copied to multiple locations. I need this to happen since I don't have to change the server that I logged into and go to a different one. It is all done in one location and I was hoping to make things easier and not write a whole bunch of little coding to go and copy and save in the folders.

like image 891
bgrif Avatar asked Jul 10 '14 14:07

bgrif


People also ask

How do I copy a file to multiple folders at once?

If you need to copy a file to multiple folders, you can hold down the Ctrl key, and drag the file or folder on to each folder you want to copy it to.

How do I copy files and folders in PowerShell?

To copy the contents of the folder to the destination folder in PowerShell, you need to provide the source and destination path of the folder, but need to make sure that you need to use a wildcard (*) character after the source path, so the entire folder content gets copied.

How do I duplicate a file in PowerShell?

We can use PowerShell to copy a file from one location to another with the Copy-Item cmdlet. The location can be another local folder or a remote computer. Besides files, we can also copy complete folders with subfolders and content. And it's even possible to filter the files that we copy.


1 Answers

copy-item only takes a single value for its -destination parameter, so you need a loop of some type.

Assuming you want the same file name in multiple folders:

$destFolders | Foreach-Object { Copy-Item -Path $Source -dest (Join-Path $_ $destFileName) }

should do it.

like image 95
Richard Avatar answered Nov 13 '22 05:11

Richard