Share via


Using PowerShell to Copy a Single File to Multiple Folders

The Copy-Item command does as its name suggests and copies objects from one path to another. It does not however provision for the ability to copy one object to multiple locations.

The Get-ChildItem command retrieves an array of objects within a supplied directory. It does not however afford the ability to put child objects into the array of child objects.

The ForEach-Object command loops on an array of objects performing the tasks contained within its brackets.

#The purpose of this script is to take a file and copy it to each of the subfolders it is run in

Function fanCopy-item
{
Param
(
[string]$source= 'C:\Users\Mr. Marshall\Documents\My Documents\Clients\S-Z\T\Thomas Marshall\Computing Professional\Cover Letter.docx',

[string]$destination,

[string]$overwritePrompt
)

Process
{
# check the supplied source parameter value:
if(test-path-path $source) {$renFile=  split-path $source-leaf-resolve}else {echo "Invalid source path provided."}

# check the supplied destination parameter value:
if(!$destination) {$destination =get-location}
if(!(get-childitem -path $destination-exclude*.*)) {echo"No child directories to copy to."}
if($overwritePrompt -eq"y") {$overwritePrompt='-Confirm'}else {$overwritePrompt =''}


get-childitem -path $destination-exclude*.* |
Foreach-object { powershell-command"copy-item '$($source)' -destination '$($destination)\$($_.name)\$($_.name)-$($renFile)' $($overwritePrompt)"} 
#An interesting note is that echos the location and I should've noticed the cover letter being copied to each of the subfolders in my user.
}
}

NOTE: This is a stub article. Please add more information as it becomes available.