Copy-Item Doesn't Recursively Replace In Destination

Hello All

New to Powershell and this forum so please bear with me

I have a requirement to copy a handful of files in my source directory over every instance of that filename in my destination directory (including instances in sub-folders)

I have this so far:-

$sourceDirectory = “C:\Source”
$destinationDirectory = “C:\Destination”

$sourceFolders = Get-ChildItem -Path $sourceDirectory | Select-Object -ExpandProperty Name
$destinationFolders = Get-ChildItem -Path $destinationDirectory | Select-Object -ExpandProperty Name

$matchesInBoth = $sourceFolders | Where-Object{$destinationFolders -contains $}
$matchesInBoth | ForEach-Object{
$sourcePath = (Join-Path $sourceDirectory $
)
Copy-Item -Path $sourcePath -Destination $destinationDirectory -Recurse

}

This copies successfully over the matching file names in the root of “C:\Destination” but not over the matching file names within the sub-folders of C:\Destination

Plenty of googling and playing with the syntax but this remains as close as I can get.

Help greatly appreciated

Adam

 

 

 

 

 

Use the -Force parameter.

-Force Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a read-only file or alias. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6

We all love PowerShell, but it is not always the best answer for everything.
You could just use the built-in Windows robocopy to do this.

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy

FYI… You can use PowerShell and robocopy together.

Robocopy and PowerShell
This script allow you to run the Robocopy comand with powershell with various folders.When you donwload this script you’ll have to edit it and change the source and destination folders.
https://gallery.technet.microsoft.com/scriptcenter/Robocopy-and-PowerShell-8e3d8011

You can simplify this…

$sourceFolders = Get-ChildItem -Path $sourceDirectory | Select-Object -ExpandProperty Name
$destinationFolders = Get-ChildItem -Path $destinationDirectory | Select-Object -ExpandProperty Name

… to this…

$sourceFolders = (Get-ChildItem -Path $sourceDirectory).Name
$destinationFolders = (Get-ChildItem -Path $destinationDirectory).Name